diff --git a/Dockerfile b/Dockerfile old mode 100755 new mode 100644 index 9d676ed3..f05c82d6 --- a/Dockerfile +++ b/Dockerfile @@ -1,42 +1,143 @@ -# Copyright (C) 2018-2020 LEIDOS. -# +# Copyright (C) 2018-2021 LEIDOS. +# # 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. -FROM usdotfhwastoldev/carma-base:develop as deps +FROM ubuntu:18.04 -FROM deps as setup +MAINTAINER Leidos, Inc. +LABEL Description="Dockerised Simulation of Carla_Sumo_Mosaic" -RUN mkdir ~/src -COPY --chown=carma . /home/carma/src/ -RUN ~/src/docker/checkout.sh -RUN ~/src/docker/install.sh +ENV SUMO_HOME /usr/share/sumo +ENV SUMO_USER carla_sumo_mosaic -FROM deps -ARG BUILD_DATE="NULL" -ARG VERSION="NULL" -ARG VCS_REF="NULL" +ENV CARLA_HOME /CARLA_0.9.10/ +RUN export CARLA_HOME -LABEL org.label-schema.schema-version="1.0" -LABEL org.label-schema.name="carla-ackermann-control-wrapper-driver" -LABEL org.label-schema.description="carla ackermann control wrapper driver for the CARMA Platform" -LABEL org.label-schema.vendor="Leidos" -LABEL org.label-schema.version=${VERSION} -LABEL org.label-schema.url="https://highways.dot.gov/research/research-programs/operations/CARMA" -LABEL org.label-schema.vcs-url="https://github.com/usdot-fhwa-stol/carma-simulation/" -LABEL org.label-schema.vcs-ref=${VCS_REF} -LABEL org.label-schema.build-date=${BUILD_DATE} +RUN apt-get update && \ + apt-get install -y openjdk-8-jdk && \ + apt-get install -y ant && \ + apt-get clean && \ + rm -rf /var/lib/apt/lists/ && \ + rm -rf /var/cache/oracle-jdk8-installer; -COPY --from=setup /home/carma/install /opt/carma/install +ENV JAVA_HOME /usr/lib/jvm/java-8-openjdk-amd64/ +RUN export JAVA_HOME -CMD [ "wait-for-it.sh", "localhost:11311", "--", "roslaunch", "carla_ackermann_control_wrapper", "carla_ackermann_control_wrapper.launch"] +RUN apt-get -y update + +RUN apt-get install x11-xserver-utils dconf-editor dbus-x11 -y + +RUN apt-get update && apt-get upgrade -y && apt-get clean + +# Python package management and basic dependencies +RUN apt-get install -y curl python3.7 python3.7-dev python3.7-distutils + +# Register the version in alternatives +RUN update-alternatives --install /usr/bin/python python /usr/bin/python3.7 1 + +# Set python 3 as the default python +RUN update-alternatives --set python /usr/bin/python3.7 + +RUN curl -s https://bootstrap.pypa.io/get-pip.py -o get-pip.py && \ + python get-pip.py --force-reinstall && \ + rm get-pip.py + +RUN pip3.7 install lxml + +# Dependencies for glvnd and X11. +RUN apt-get update \ + && apt-get install -y -qq --no-install-recommends \ + libglvnd0 \ + libgl1 \ + libglx0 \ + libegl1 \ + libxext6 \ + libx11-6 \ + && rm -rf /var/lib/apt/lists/* + +# Env vars for the nvidia-container-runtime. +ENV NVIDIA_VISIBLE_DEVICES all +ENV NVIDIA_DRIVER_CAPABILITIES graphics,utility,compute + +RUN apt-get update && \ + apt-get install -y software-properties-common && \ + rm -rf /var/lib/apt/lists/* + +# Install python3.6 for NS-3 installation +RUN add-apt-repository ppa:deadsnakes/ppa && \ + apt update && \ + apt install python3.6 + +# Install other dependencies +RUN apt-get update && \ + apt-get install -y g++ gcc unzip tar python3-dev && \ + apt-get install -y autoconf automake libtool curl make && \ + apt-get install -y libxml2 libsqlite3-dev && \ + apt-get install -y libxml2-dev + +RUN \ + apt-get update && \ + apt-get install -y --allow-unauthenticated \ + build-essential \ + pkg-config \ + lbzip2 \ + libprotobuf-dev \ + libsqlite3-dev \ + protobuf-compiler \ + patch \ + rsync \ + wget + +# Install vim as text editor +RUN apt-get install -y vim + +RUN apt-get install -y nano + +RUN apt-get install -y xterm + +RUN apt install -y default-jdk + +# Install SUMO +RUN add-apt-repository ppa:sumo/stable + +RUN apt-get update + +RUN apt-get install -y \ + sumo \ + sumo-tools \ + sumo-doc + +RUN adduser $SUMO_USER --disabled-password + +# Enable sudo +RUN apt-get update && apt-get install -y sudo + +RUN adduser $SUMO_USER sudo --disabled-password + +COPY co-simulation/traci_update/connection.py ./usr/share/sumo/tools/traci/ +COPY co-simulation/traci_update/constants.py ./usr/share/sumo/tools/traci/ +COPY co-simulation/traci_update/main.py ./usr/share/sumo/tools/traci/ + +RUN echo '%sudo ALL=(ALL) NOPASSWD:ALL' >> \ +/etc/sudoers + + +### Docker (Optional) ### +# RUN apt-get update && \ +# apt-get -qy full-upgrade && \ +# apt-get install -qy curl && \ +# apt-get install -qy curl && \ +# curl -sSL https://get.docker.com/ | sh + +# RUN adduser $SUMO_USER docker --disabled-password diff --git a/Instruction/Build Docker Image Instruction/README.md b/Instruction/Build Docker Image Instruction/README.md new file mode 100644 index 00000000..b380489f --- /dev/null +++ b/Instruction/Build Docker Image Instruction/README.md @@ -0,0 +1,159 @@ +# Running CARLA-SUMO-MOSAIC Co-Simulation Tool with NS-3 Integration in Docker + +This is the tutorial to run CARLA-SUMO-MOSAIC co-simulation tool in a docker container. It is recommended to run the co-simulation tool on a **high-performance** computer. + +## Test Platform + +- Operating System: Ubuntu 20.04.2 LTS +- CPU: Intel(R) Core(TM) i7-9700K CPU @ 3.60 GHz +- RAM: 16 GB +- Graphics: NVIDIA GeForce RTX 2070 Super 8 GB + +## Prerequisites + +- NVIDIA GPU with at least 8 GB +- NVIDIA drivers > 361.93 +- Free Disk Space > 30 GB +- NVIDIA Container Toolkit +- Docker + +If you do not have Docker installed, please refer to this [link](https://usdot-carma.atlassian.net/wiki/spaces/CRMPLT/pages/486178841/Setup+CARMA+Platform+Prerequisites#Install-docker-using-docker-install.sh-in-CARMA-Platform-repo) for installation. + +If you do not have NVIDIA Container Toolkit installed, please refer to this [link](https://usdot-carma.atlassian.net/wiki/spaces/CRMPLT/pages/486178841/Setup+CARMA+Platform+Prerequisites#CUDA-11.2-(Non-VM-installation)) for installation. + +## Build/Pull Docker Image of Co-Simulation Tool + +There are two ways to get co-simulation docker image. You can either choose to pull the co-simulation tool docker image from DockerHub or build the image by yourself. + +#### Option 1, Pull Docker Image + +To pull the co-simulation tool from DockerHub, make sure that you have been installed the docker tool into your system and have been login your personal account. + +##### Step 1: Simply type the command to pull the docker image: + +```sh +docker pull usdotfhwastol/carma-xil-cosimulation:[tag] +``` + +The tag information could be found from [usdotfhwastol Dockerhub](https://hub.docker.com/repository/docker/usdotfhwastol/carma-xil-cosimulation/tags?page=1&ordering=last_updated) + +##### Step 2: Run docker image with a container: + +```sh +cd /docker && ./run.sh -v [version] +``` + +Once you access the conainer, skip the option 2 and go to the `Run carma-xil-cosimulation` step to test the co-simulation + +#### Option 2, Build Docker Image +##### Prerequisites + +To build the co-simulation tool docker image, the executable `carla_sumo_mosaic` file should be created firstly. The executable zip file located at the co-simulation folder as the name `carla-sumo-mosaic-[version].zip`. Extract the all contents into an empty folder with the name `carla_sumo_mosaic` then remember the directory of the folder for the later usage + +##### Step 1: Build image from Dockerfile by using following command: + +```sh +cd /docker && ./build-image.sh -v [version] +``` + +##### Step 2: Run docker image with a docker container + +```sh +cd /docker && ./run.sh -v [version] +``` + +##### Step 3: Copy CARLA and Co-Simulation tool + +Copy `CARLA_0.9.10`, executable `carla_sumo_mosaic` and `bridge` into the container. + +``` +docker cp /CARLA_0.9.10 :./ +docker cp /carla_sumo_mosaic :./ +docker cp /co-simulation/bridge :./ +``` + +##### Step 4: Unzip scenarios from sample_scenario.zip at co-simulation folder and copy to docker + +``` +docker cp /Town04_20 :./carla_sumo_mosaic/scenarios +``` + +### Modify files in Docker Container + +#### Step 1: Modify `ns3_installer.sh` + +In Docker container, type: + +```sh +cd carla_sumo_mosaic/bin/fed/ns3 +``` + +Then modify `ns3_installer.sh` by: + +``` +vim ns3_installer.sh +``` + +(If you see a message `vim: command not found`, please use `sudo apt-get install vim` to install vim as text editor) + +In the `build_ns3()` function, after `CXXFLAGS="-Wno-error" python3.6 ./build.py --disable-netanim`, add the following command + +``` +sudo cp -ar ns-3.28/build/ns3 /usr/include/ +``` + +#### Step 2: Build NS-3 + +In directory `carla_sumo_mosaic/bin/fed/ns3`, type: + +``` +./ns3_installer.sh +``` + +Once all 1947 files are compiled and a successful message shows up, it means NS-3 is successful installed. + +#### Step 3: Add NS-3 as environment variable + +``` +export NS3_HOME='/carla_sumo_mosaic/bin/fed/ns3' +``` + +Use `printenv` to check if NS-3 is successful added to environment variable. + +#### Step 4: Modify `run.sh` + +In directory `carla_sumo_mosaic/bin/fed/ns3`, type: + +``` +vim run.sh +``` + +Change line 11 to: + +``` +LD_LIBRARY_PATH=/carla_sumo_mosaic/bin/fed/ns3/ns-allinone-3.28/ns-3.28/build /carla_sumo_mosaic/bin/fed/ns3/ns-allinone-3.28/ns-3.28/build/scratch/mosaic_starter --port=$port --cmdPort=$cmdport --configFile=scratch/ns3_federate_config.xml +``` + +## Run Co-Simulation Tool + +Once everything is ready, under directory `/carla_sumo_mosaic`, simply type: + +``` +./mosaic.sh -s Town04_20 +``` + +The command will start CARLA, SUMO and x-terminal showing the CALRA-MOSAIC loading status + +![carla_sumo_mosaic_ready](../../co-simulation/doc/gif/ready.gif) + +When the x-terminal showing the CARLA-MOSAIC status is connected, simply click the SUMO play button to start the program + +![carla_sumo_mosaic](../../co-simulation/doc/gif/carla_sumo_mosaic_demo.gif) + +***Note: Current CARMA XIL Version has a known issue with a port conflict between NS-3 and CARMA-CARLA integration see [#39](https://github.com/usdot-fhwa-stol/carma-simulation/issues/39). The recommended workaround is to run exclusively one or the other module.*** + +### Commit the container back to image +After the run if there is no issue, commit docker container to docker image +``` +docker container commit usdotfhwastol/carma-xil-cosimulation:[tag] +``` diff --git a/co-simulation/README.md b/Instruction/Build MOSAIC Instruction/README.md similarity index 95% rename from co-simulation/README.md rename to Instruction/Build MOSAIC Instruction/README.md index b2f09069..d7d448e3 100644 --- a/co-simulation/README.md +++ b/Instruction/Build MOSAIC Instruction/README.md @@ -10,7 +10,7 @@ For a successful running of the co-simulation tool, the following software must - CARLA simulator 0.9.10 - JAVA 8 or 11 - Recommend using the [Adopt OpenJDK](https://adoptium.net/?variant=openjdk8). The environment variable **JAVA_HOME** needs be configured to the location of JDK. -- Python 3.7 - If the users use different version of Python other than 3.7, the users need to copy the CARLA library .egg file to the folder bridge/ PythonAPI /carla/dist. In addition, the package `lxml==4.5.0` needs to be installed. +- Python 3.7 - If the users use different version of Python other than 3.7, the users need to copy the CARLA library .egg file to the folder bridge/ PythonAPI /carla/dist. In addition, the package `lxml==4.5.0` needs to be installed. - SUMO 1.8.0 - The environment variable **`SUMO_HOME`** **must be configured to define the installation directory of SUMO**. - ns-3 simulator - TraCI library has to be updated. @@ -18,12 +18,12 @@ For a successful running of the co-simulation tool, the following software must Moreover, a high performance computer is needed to run the co-simulation tool. The configuration of a recommended system is in the following. - **CPU**: Intel i7 gen 9th - 11th / Intel i9 gen 9th - 11th / AMD ryzen 7 / AMD ryzen 9 -- **RAM memory:** minimum 16GB +- **RAM memory:** minimum 16GB - **Graphics card:** NVIDIA RTX 2070 / RTX 2080 / RTX 3070 / RTX 3080 ## Installation of Prerequisites -### 1. Installation of ns-3 3.28 +### 1. Installation of ns-3 3.28 #### a. Linux system @@ -92,7 +92,7 @@ Since ns-3 is primarily developed on and for GNU/Linux platforms, users can exec - Switch to the location of the ns-3 Dockerfile in **/bin/fed/ns3** and run the following command on command line. A docker image named ns3-federate will be generated. ``` - docker build -t ns3-federate . + docker build -t ns3-federate . ``` - Open etc/runtime.json, enter the name of the ns-3 docker in the ns3-section into the property dockerImage: @@ -191,7 +191,7 @@ sudo \cp main.py /usr/local/share/sumo/tools/traci Go to **bin/fed/ns3** folder of executable co-simulation tool, copy **constants.py, connection.py, and main.py** to traci folder of SUMO (**C:\Program Files (x86)\Eclipse\Sumo\tools\traci**). -### 5. Installation of CARLA 0.9.10 +### 5. Installation of CARLA 0.9.10 #### a. Linux system @@ -236,17 +236,17 @@ Go to **bin/fed/ns3** folder of executable co-simulation tool, copy **constants. ### **1.** **Executable Bundle File** -Download the co-simulation tool bundle file and extract it to an arbitrary path. +Download the co-simulation tool bundle file and extract it to an arbitrary path. ### **2.** **Installation from Source Code** -For a successfully build the co-simulation tool, Apache Maven needs to be installed. If Maven 3.1.x or higher has not been installed, please use the following steps to install it. +For a successfully build the co-simulation tool, Apache Maven needs to be installed. If Maven 3.1.x or higher has not been installed, please use the following steps to install it. #### a. Installation of Maven **Linux system** -- Download the binary distribution archive **apache-maven-3.8.3** from this [link](https://maven.apache.org/download.cgi). +- Download the binary distribution archive **apache-maven-3.8.3** from this [link](https://maven.apache.org/download.cgi). - Installation extract distribution archive in any directory @@ -260,15 +260,15 @@ For a successfully build the co-simulation tool, Apache Maven needs to be instal export PATH=path_to_apache_maven-3.8.3/apache-maven-3.8.3/bin:$PATH ``` - -- Verify the installation by running **mvn -v** in a new terminal. + +- Verify the installation by running **mvn -v** in a new terminal. **Windows system** - Download the binary distribution archive **apache-maven-3.8.3** from this [link](https://dlcdn.apache.org/maven/maven-3/3.8.3/binaries/apache-maven-3.8.3-bin.zip). - Extract compressed files and a folder named apache-maven-3.8.3 will be generated. - Add the bin directory of the created directory apache-maven-3.8.3 to the PATH environment variable. -- Verify the installation by running **mvn -v** in a new terminal. +- Verify the installation by running **mvn -v** in a new terminal. #### b. Build Co-simulation Tool @@ -298,11 +298,11 @@ For a successfully build the co-simulation tool, Apache Maven needs to be instal mvn clean install -DskipTests ``` - + - After building, go to bundle\target directory, a zip file of co-simulation bundle "**carla-sumo-mosaic-21.2.zip**" can be found. -- Extract the bundle to an arbitrary path. The installation folder is referenced as ``. +- Extract the bundle to an arbitrary path. The installation folder is referenced as ``. ## **Folder Content** @@ -321,11 +321,11 @@ The folder structure of `` is described in the following. ├─ lib ................... Directory with all Java compiled libraries required for MOSAIC. ├─ scenarios ............. Directory containing all simulation scenarios. ├─ tools ................. Additional tools, like the HTML Visualizer. - ├─ CONTRIBUTING.md - ├─ LICENSE + ├─ CONTRIBUTING.md + ├─ LICENSE ├─ mosaic.bat ............ Start script for Windows systems. └─ mosaic.sh ............. Start script for GNU/Linux systems. - + ``` ## **Co-Simulation Scenario** @@ -459,7 +459,7 @@ The bridge file (bridge.sh or bridge.bat) is used to run the bridge to connect C cd ../../../bridge -x-terminal-emulator python3.7 carla_mosaic_bridge.py --bridge-server-port 8913 --map Town04 net/Town04.net.xml --step-length 0.1 +x-terminal-emulator python3.7 carla_mosaic_bridge.py --bridge-server-port 8913 --map Town04 ../scenarios/Town04/sumo/Town04.net.xml --step-length 0.1 ``` **Windows system** @@ -467,7 +467,7 @@ x-terminal-emulator python3.7 carla_mosaic_bridge.py --bridge-server-port 8913 - ```powershell @ECHO OFF cd ../../../bridge -python carla_mosaic_bridge.py --bridge-server-port 8913 --map Town04 net/Town04.net.xml --step-length 0.1 +python carla_mosaic_bridge.py --bridge-server-port 8913 --map Town04 ../scenarios/Town04/sumo/Town04.net.xml --step-length 0.1 ``` The arguments in the above python commands are shown in the following. @@ -476,11 +476,11 @@ The arguments in the above python commands are shown in the following. **`--map Tow04`**: the map loaded in the CARLA simulator. If not specified, the default map of CARLA simulator will be used. -**`net/Town04.net.xml`**: the net file of the CARLA map or SUMO, the net file is located in the net folder under the bridge folder. Since SUMO and CARLA simulator use different reference systems, the SUMO net offset calculated from the net file is used to calculate the transform of SUMO actors in CARLA simulator and the transform of CARLA actors in SUMO. If not specified, the net file will be generated using the CARLA map. +**`../scenarios/Town04/sumo/Town04.net.xml`**: the net file of the CARLA map or SUMO, the net file is located in the net folder under the bridge folder. Since SUMO and CARLA simulator use different reference systems, the SUMO net offset calculated from the net file is used to calculate the transform of SUMO actors in CARLA simulator and the transform of CARLA actors in SUMO. If not specified, the net file will be generated using the CARLA map. **--step-length**: the simulation step length, which should be the same as the updateInterval of CARLA. -### 4. Carma Configuration File +### 4. CARMA Configuration File The CARMA ambassador can be configured with the CARMA configuration file. The specific path is **/carma/carma_config.json**. An example configuration files of CARMA ambassador is shown in the following. @@ -496,12 +496,12 @@ The CARMA ambassador can be configured with the CARMA configuration file. The sp "vehicleType": "vehicle.chevrolet.impala", "applications":["org.eclipse.mosaic.app.tutorial.VehicleCommunicationApp"], "geoPosition": { - "latitude": 52.579272059028646, + "latitude": 52.579272059028646, "longitude": 13.467165499469328 }, "projectedPosition": { - "x": 501.62, + "x": 501.62, "y": 116.95 }, @@ -554,11 +554,11 @@ The Mapping ambassador can be configured with the mapping configuration file. Th ### 7. NS-3 Configuration File -The ns-3 ambassador and ns-3 federate can be configured with the configuration files. The specific path is **/ns3/**. Please refer to this [link](https://www.eclipse.org/mosaic/docs/simulators/network_simulator_ns3/#configuration) for more information about the configuration file. +The ns-3 ambassador and ns-3 federate can be configured with the configuration files. The specific path is **/ns3/**. Please refer to this [link](https://www.eclipse.org/mosaic/docs/simulators/network_simulator_ns3/#configuration) for more information about the configuration file. ## **Run a Co-simulation Scenario** -To run a co-simulation scenario via Command Line Interface, call the start script with the following command line arguments. For more CLI options, please refer to Eclipse MOSAIC documentation. After CARLA loads map and SUMO GUI pops out, click the play button in SUMO GUI to start running co-simulation. +To run a co-simulation scenario via Command Line Interface, call the start script with the following command line arguments. For more CLI options, please refer to Eclipse MOSAIC documentation. After CARLA loads map and SUMO GUI pops out, click the play button in SUMO GUI to start running co-simulation. **GNU/Linux** @@ -592,7 +592,7 @@ mosaic.bat -s Co-simulation -v -w 0 ## **Check the Log Files** -Log files are generated for the used ambassadors for each simulation run. They are stored in the folder `/logs/log--scenarioname`. Each simulation run has a new log file folder generated. The folder structure of log file folder looks like the following. The log file Carla.log is about CARLA ambassador. +Log files are generated for the used ambassadors for each simulation run. They are stored in the folder `/logs/log--scenarioname`. Each simulation run has a new log file folder generated. The folder structure of log file folder looks like the following. The log file Carla.log is about CARLA ambassador. ``` └─ log--secarioname @@ -621,7 +621,3 @@ If the maps of CARLA for the scenarios is the same as the default map of CARLA s Sometimes, the CARLA client may not be connected to CARLA simulator. Check whether there is a CARLA process running in the background or not. If so, terminate the CARLA process. During the simulation, change the view of spectator may cause the CARLA simulator freeze. Users should adjust the view of spectator before starting the co-simulation. - - - - \ No newline at end of file diff --git a/carla-carma-integration/Dockerfile b/carla-carma-integration/Dockerfile deleted file mode 100644 index c917b5f7..00000000 --- a/carla-carma-integration/Dockerfile +++ /dev/null @@ -1,86 +0,0 @@ -# Copyright (C) 2021 LEIDOS. -# -# 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. -FROM ros:kinetic -WORKDIR /home - -ARG CARMA_VERSION="carma-system-3.9.0" - -# CARLA PythonAPI -RUN mkdir ./PythonAPI -ADD https://carla-releases.s3.eu-west-3.amazonaws.com/Backup/carla-0.9.10-py2.7-linux-x86_64.egg ./PythonAPI - -RUN apt-get update && apt-get install -y \ - git \ - curl \ - wget \ - nano \ - libpng16-16 \ - libsdl2-2.0 \ - software-properties-common - -# Update gcc and g++ -RUN add-apt-repository ppa:ubuntu-toolchain-r/test -RUN apt-get update && apt-get install -y \ - gcc-6 \ - g++-6 - -# CARLA ROS Bridge -RUN git clone --depth 1 -b '0.9.10.1' --recurse-submodules https://github.com/carla-simulator/ros-bridge.git - -# CARLA-CARMA integration tool copy from local -COPY . ./carla-carma-integration - -# CARLA-CARMA integration tool necessary package and msgs -RUN apt-get install -y --no-install-recommends \ - python-pip \ - python-wheel \ - ros-kinetic-ackermann-msgs \ - ros-kinetic-derived-object-msgs \ - ros-kinetic-jsk-recognition-msgs \ - ros-kinetic-rqt \ - ros-kinetic-rviz \ - ros-kinetic-pcl-conversions \ - ros-kinetic-pcl-ros \ - ros-kinetic-cv-bridge - -# Upgrade CMake to 3.13 -RUN wget https://cmake.org/files/v3.13/cmake-3.13.0-Linux-x86_64.tar.gz -RUN tar -xzvf cmake-3.13.0-Linux-x86_64.tar.gz -RUN mv cmake-3.13.0-Linux-x86_64 /opt/cmake-3.13.0 -RUN ln -sf /opt/cmake-3.13.0/bin/* /usr/bin/ -RUN rm cmake-3.13.0-Linux-x86_64.tar.gz - -# Clone ROS message -RUN mkdir -p msgs -RUN cd msgs \ - && git clone -b ${CARMA_VERSION} https://github.com/usdot-fhwa-stol/autoware.ai.git \ - && git clone -b ${CARMA_VERSION} https://github.com/usdot-fhwa-stol/carma-msgs.git - -# Catkin make for both ros-bridge and carla-carma-integration -RUN mkdir -p carla_carma_ws/src/msgs - -RUN cd carla_carma_ws/src/msgs \ - && ln -s ../../../msgs/carma-msgs/j2735_msgs \ - && ln -s ../../../msgs/carma-msgs/cav_msgs \ - && ln -s ../../../msgs/autoware.ai/messages/autoware_msgs - -RUN cd carla_carma_ws/src \ - && ln -s ../../ros-bridge \ - && ln -s ../../carla-carma-integration \ - && cd .. \ - && /bin/bash -c '. /opt/ros/kinetic/setup.bash; catkin_make' - -RUN pip install simple-pid - -CMD ["/bin/bash"] diff --git a/carla-carma-integration/README.md b/carla-carma-integration/README.md deleted file mode 100644 index 09b8350e..00000000 --- a/carla-carma-integration/README.md +++ /dev/null @@ -1,93 +0,0 @@ -# CARAL-CARMA Integration Tool -This user guide provides step-by-step user instructions on how to build the CARLA-CARMA integration tool on Docker, setup configuration for both CARMA platform and CARLA-CARMA integration tool and run that with CARMA platform. - -## Requirement -- Docker (19.03+) -- [Nvidia Docker](https://github.com/NVIDIA/nvidia-docker) -- [CARMA Platform](https://usdot-carma.atlassian.net/wiki/spaces/CRMPLT/pages/486178827/Development+Environment+Setup) (3.9.0) - -## Setup -### CARLA-CARMA Integration tool -1. clone the CARMA simulation repository: - -``` -git clone https://github.com/usdot-fhwa-stol/carma-simulation.git -``` -2. build image from Dockerfile by using following command: - -```sh -cd carma-simulation/carla-carma-integration && ./build-image.sh -``` -After built the image successfully, the CARLA-CARMA integration tool docker image will be generated. - -### CARMA Platform config -The CARMA Config for the simulation currently cannot be pulled from docker hub. It requires local docker build for the image. - -1. Clone the source code of CARMA config from github: -```sh -git clone https://github.com/usdot-fhwa-stol/carma-config.git -``` -2. Go to the directory /carla_integration under CARMA config and build the docker image. Remember the image name -```sh -cd ~/carma-config/carla_integration/ -./build-image.sh -``` -3. SetupCARMA config of the simulation -```sh -carma config set usdotfhwastol/carma-config:[tag] -``` -## Run CARLA-CARMA integration tool with CARMA Platform -1. Run CARLA server - -``` -./CarlaUE4.sh -``` -2. Run CARMA Platform with separated terminal -``` -carma start all -``` - -3. Run CARLA-CAMRA integration tool docker image by using run.sh file in the direction **`carma-simulation/carla-carma-integration`**, setting the catkin source and Python path, and launch the tool when get into container -``` -./run.sh -``` -``` -export PYTHONPATH=$PYTHONPATH:/home/PythonAPI/carla-0.9.10-py2.7-linux-x86_64.egg && source /home/carla_carma_ws/devel/setup.bash -``` -``` -roslaunch carla_carma_agent carla_carma_agent.launch -``` -Once CARLA-CARMA integration tool has been launched, the CARMA corresponding CARLA vehicle will be generated in CARLA server. - -4. Open CARMA-Web-UI for selecting route and plugins via Chromium Web Browser then click the circle button at the left bottom corner. - -![CARMA-Web-UI](docs/images/CARMA-Web-UI.png) - -Afterward, the corresponding CARLA vehicle will start to receive control command from CARMA-Platform and start to following the selected route to move - -## Usage instruction -The usage instruction including what parameter could be parsed to CALRA-CARMA integration tool launch file and the description of these parameters - -### CARLA-CARMA Integration parameters -| Parameters| **Description**|*Default*| -| ------------------- | ------------------------------------------------------------ |----------| -|host|CARLA server IP address|127.0.0.1| -|port|CARLA server port number|2000| -|town|To specify which scenario for CARLA server to load. The scenario should be matched with executed CARMA Platform vector_map|Town02| -|spawn_point|To specify where to spawn CARLA vehicle|N/A| -|role_name|Assign the name of the CARLA vehicle. It currently only supports the name range from hero0 to hero9 and ego_vehicle|ego_vehicle| -|vehicle_modle|To specify what vehicle model should be generated in CARLA server|vehicle.toyota.prius| -|vehicle_length|To specify the length of vehicle|5.00| -|vehicle_width|To specify the width of vehicle|3.00| -|vehicle_wheelbase|To specify the size of wheelbase for the vehicle|2.79| -|speed_Kp| Speed proportional value for the vehicle. The current default value was setup for Town02 with vehicle speed limit 20 MPH|0.05| -|speed_Ki| Speed integral value for the vehicle. The current default value was setup for Town02 with vehicle speed limit 20 MPH|0.018| -|speed_Kp| Speed derivative value for the vehicle. The current default value was setup for Town02 with vehicle speed limit 20 MPH|0.4| -|accel_Kp| Acceleration proportional value for the vehicle. The current default value was setup for Town02 with vehicle speed limit 20 MPH|0.053| -|accel_Ki| Acceleration integral value for the vehicle. The current default value was setup for Town02 with vehicle speed limit 20 MPH|0.0| -|accel_Kd| Acceleration derivative value for the vehicle. The current default value was setup for Town02 with vehicle speed limit 20 MPH|0.052| -|init_speed| To specify the initial vehicle speed |5| -|init_acceleration| To specify the initial vehicle acceleration |1| -|init_steering_angle| To specify the initial vehicle steering wheel angle, it range from 0.7(left) to -0.7(right)|0| -|init_jerk| To specify the initial vehicle jerk value|0| -|driver_name| To specify the name to the topic of `/hardware_interface/driver_discovery`. This name should be configured exact same with `required_drivers` in VehicleConfigParams.yaml in CARMA config| /hardware/carla_driver| diff --git a/carla-carma-integration/build-image.sh b/carla-carma-integration/build-image.sh deleted file mode 100755 index 1ef1ce18..00000000 --- a/carla-carma-integration/build-image.sh +++ /dev/null @@ -1,2 +0,0 @@ -#!/bin/sh -docker build -t usdotfhwastol/carla-carma-integration -f Dockerfile . "$@" diff --git a/carla-carma-integration/carla-carma-agent/CMakeLists.txt b/carla-carma-integration/carla-carma-agent/CMakeLists.txt deleted file mode 100644 index ef8a31fa..00000000 --- a/carla-carma-integration/carla-carma-agent/CMakeLists.txt +++ /dev/null @@ -1,20 +0,0 @@ -# Copyright (c) 2021 Intel Corporation -# This work is licensed under the terms of the MIT license. -# For a copy, see . - -cmake_minimum_required(VERSION 2.8.3) -project(carla_carma_agent) - -find_package(catkin REQUIRED COMPONENTS - roslaunch -) - -catkin_package() - -install(DIRECTORY agent/ - DESTINATION ${CATKIN_PACKAGE_SHARE_DESTINATION}/agent -) - -install(DIRECTORY launch/ - DESTINATION ${CATKIN_PACKAGE_SHARE_DESTINATION}/launch -) diff --git a/carla-carma-integration/carla-carma-agent/agent/bridge.launch b/carla-carma-integration/carla-carma-agent/agent/bridge.launch deleted file mode 100644 index bde7ded5..00000000 --- a/carla-carma-integration/carla-carma-agent/agent/bridge.launch +++ /dev/null @@ -1,113 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - > - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/carla-carma-integration/carla-carma-agent/agent/config/sensors.json b/carla-carma-integration/carla-carma-agent/agent/config/sensors.json deleted file mode 100644 index 769bade6..00000000 --- a/carla-carma-integration/carla-carma-agent/agent/config/sensors.json +++ /dev/null @@ -1,121 +0,0 @@ -{ - "sensors": [ - { - "type": "sensor.camera.rgb", - "id": "front", - "x": 4.0, "y": 0.0, "z": 0.57, "roll": 0.0, "pitch": 0.0, "yaw": 0.0, - "image_size_x": 800, - "image_size_y": 600, - "fov": 120.0, - "sensor_tick": 0.05, - "gamma": 2.2, - "shutter_speed": 200.0, - "iso": 100.0, - "fstop": 8.0, - "min_fstop": 1.2, - "blade_count": 5, - "exposure_mode": "histogram", - "exposure_compensation": 0.0, - "exposure_min_bright": 7.0, - "exposure_max_bright": 9.0, - "exposure_speed_up": 3.0, - "exposure_speed_down": 1.0, - "calibration_constant": 16.0, - "focal_distance": 1000.0, - "blur_amount": 1.0, - "blur_radius": 0.0, - "motion_blur_intensity": 0.45, - "motion_blur_max_distortion": 0.35, - "motion_blur_min_object_screen_size": 0.1, - "slope": 0.88, - "toe": 0.55, - "shoulder": 0.26, - "black_clip": 0.0, - "white_clip": 0.04, - "temp": 6500.0, - "tint": 0.0, - "chromatic_aberration_intensity": 0.0, - "chromatic_aberration_offset": 0.0, - "enable_postprocess_effects": "True", - "lens_circle_falloff": 5.0, - "lens_circle_multiplier": 0.0, - "lens_k": -1.0, - "lens_kcube": 0.0, - "lens_x_size": 0.08, - "lens_y_size": 0.08, - "bloom_intensity": 0.675, - "lens_flare_intensity": 0.1 - }, - { - "type": "sensor.other.gnss", - "id": "novatel_gnss", - "x": 0.0, "y": 0.0, "z": 0.0, - "noise_alt_stddev": 0.0, "noise_lat_stddev": 0.0, "noise_lon_stddev": 0.0, - "noise_alt_bias": 0.0, "noise_lat_bias": 0.0, "noise_lon_bias": 0.0 - }, - { - "type": "sensor.other.imu", - "id": "novatel_imu", - "x": 0.0, "y": 0.0, "z": 0.0, "roll": 0.0, "pitch": 0.0, "yaw": 0.0, - "noise_accel_stddev_x": 0.0, "noise_accel_stddev_y": 0.0, "noise_accel_stddev_z": 0.0, - "noise_gyro_stddev_x": 0.0, "noise_gyro_stddev_y": 0.0, "noise_gyro_stddev_z": 0.0, - "noise_gyro_bias_x": 0.0, "noise_gyro_bias_y": 0.0, "noise_gyro_bias_z": 0.0 - }, - { - "type": "sensor.lidar.ray_cast", - "id": "lidar", - "x": 1.02, "y": 0.0, "z": 2.23, "roll": 0.0, "pitch": 0.0, "yaw": 0.0, - "range": 100, - "channels": 64, - "points_per_second": 320000, - "upper_fov": 2.0, - "lower_fov": -20, - "rotation_frequency": 20 - }, - { - "type": "sensor.other.radar", - "id": "radar_fl", - "x": 3.42, "y": 1.02, "z": 0.535, "roll": 0.0, "pitch": 0.0, "yaw": 0.953, - "horizontal_fov": 30.0, - "vertical_fov": 10.0, - "points_per_second": 1500, - "range": 100.0 - }, - { - "type": "sensor.other.radar", - "id": "radar_fc", - "x": 4.0, "y": 0.0, "z": 0.57, "roll": 0.0, "pitch": 0.0, "yaw": 0.0, - "horizontal_fov": 30.0, - "vertical_fov": 10.0, - "points_per_second": 1500, - "range": 100.0 - }, - { - "type": "sensor.other.radar", - "id": "radar_fr", - "x": 3.42, "y": -1.02, "z": 0.535, "roll": 0.0, "pitch": 0.0, "yaw": -0.903, - "horizontal_fov": 30.0, - "vertical_fov": 10.0, - "points_per_second": 1500, - "range": 100.0 - }, - { - "type": "sensor.other.radar", - "id": "radar_rl", - "x": -0.85, "y": 1.05, "z": 0.535, "roll": 0.0, "pitch": 0.0, "yaw": 2.042, - "horizontal_fov": 30.0, - "vertical_fov": 10.0, - "points_per_second": 1500, - "range": 100.0 - }, - { - "type": "sensor.other.radar", - "id": "radar_rr", - "x": -0.85, "y": -1.05, "z": 0.535, "roll": 0.0, "pitch": 0.0, "yaw": -1.992, - "horizontal_fov": 30.0, - "vertical_fov": 10.0, - "points_per_second": 1500, - "range": 100.0 - } - ] -} diff --git a/carla-carma-integration/carla-carma-agent/launch/carla_carma_agent.launch b/carla-carma-integration/carla-carma-agent/launch/carla_carma_agent.launch deleted file mode 100644 index 171c775d..00000000 --- a/carla-carma-integration/carla-carma-agent/launch/carla_carma_agent.launch +++ /dev/null @@ -1,118 +0,0 @@ - - - - - - - > - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/carla-carma-integration/carla-carma-agent/package.xml b/carla-carma-integration/carla-carma-agent/package.xml deleted file mode 100644 index 48ef68e7..00000000 --- a/carla-carma-integration/carla-carma-agent/package.xml +++ /dev/null @@ -1,10 +0,0 @@ - - - carla_carma_agent - 0.0.1 - The carla_carma_agent package - carma - Apache 2.0 License - catkin - carla_carma_bridge - diff --git a/carla-carma-integration/carla_carma_bridge/CMakeLists.txt b/carla-carma-integration/carla_carma_bridge/CMakeLists.txt deleted file mode 100644 index a4d985e4..00000000 --- a/carla-carma-integration/carla_carma_bridge/CMakeLists.txt +++ /dev/null @@ -1,30 +0,0 @@ -# Copyright (c) 2021 Intel Corporation -# This work is licensed under the terms of the MIT license. -# For a copy, see . - -cmake_minimum_required(VERSION 2.8.3) -project(carla_carma_bridge) - -find_package(catkin REQUIRED COMPONENTS - autoware_msgs - rospy - cav_msgs -) - -catkin_python_setup() - -catkin_package() - -catkin_install_python(PROGRAMS - src/carla_carma_bridge/carma_carla_driver_status - src/carla_carma_bridge/carma_carla_robot_status - src/carla_carma_bridge/carla_to_carma_vehicle_status - src/carla_carma_bridge/carla_to_carma_localization - src/carla_carma_bridge/carma_to_carla_ackermann_cmd - src/carla_carma_bridge/carla_to_carma_external_objects - DESTINATION ${CATKIN_PACKAGE_BIN_DESTINATION} -) - -install(DIRECTORY launch/ - DESTINATION ${CATKIN_PACKAGE_SHARE_DESTINATION}/launch -) diff --git a/carla-carma-integration/carla_carma_bridge/launch/carla_carma_bridge.launch b/carla-carma-integration/carla_carma_bridge/launch/carla_carma_bridge.launch deleted file mode 100644 index 07ea51c7..00000000 --- a/carla-carma-integration/carla_carma_bridge/launch/carla_carma_bridge.launch +++ /dev/null @@ -1,71 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/carla-carma-integration/carla_carma_bridge/package.xml b/carla-carma-integration/carla_carma_bridge/package.xml deleted file mode 100644 index 47d102d8..00000000 --- a/carla-carma-integration/carla_carma_bridge/package.xml +++ /dev/null @@ -1,21 +0,0 @@ - - - carla_carma_bridge - 0.0.0 - The carla_carma_bridge package - - carma - Apache 2.0 License - catkin - rospy - autoware_msgs - carla_msgs - geometry_msgs - nav_msgs - rospy - autoware_msgs - carla_msgs - cav_msgs - - - diff --git a/carla-carma-integration/carla_carma_bridge/setup.py b/carla-carma-integration/carla_carma_bridge/setup.py deleted file mode 100644 index 13bf3445..00000000 --- a/carla-carma-integration/carla_carma_bridge/setup.py +++ /dev/null @@ -1,14 +0,0 @@ -# Copyright (c) 2021 Intel Corporation -# This work is licensed under the terms of the MIT license. -# For a copy, see . - -# -*- coding: utf-8 -*- -from distutils.core import setup -from catkin_pkg.python_setup import generate_distutils_setup - -d = generate_distutils_setup( - packages=['carla_carma_bridge'], - package_dir={'': 'src'}, -) - -setup(**d) diff --git a/carla-carma-integration/carla_carma_bridge/src/carla_carma_bridge/carla_to_carma_external_objects b/carla-carma-integration/carla_carma_bridge/src/carla_carma_bridge/carla_to_carma_external_objects deleted file mode 100755 index ca0015e2..00000000 --- a/carla-carma-integration/carla_carma_bridge/src/carla_carma_bridge/carla_to_carma_external_objects +++ /dev/null @@ -1,163 +0,0 @@ -#!/usr/bin/env python -# Copyright (C) 2021 LEIDOS. -# -# 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 file is loosely based on the reference architecture developed by Intel Corporation for Leidos located here -# https://github.com/41623134/carla-autoware/blob/master/catkin_ws/src/carla_autoware_bridge/src/carla_autoware_bridge/carla_to_autoware_detected_objects -# -# That file has the following license and some code snippets from it may be present in this file as well and are under the same license. -# -# Copyright (c) 2018-2019 Intel Corporation -# -# This work is licensed under the terms of the MIT license. -# For a copy, see . -# - - -""" -ground truth detections. Publishes the following topics: - /environment/external_objects (cav_msgs::ExternalObjectList) -""" -import rospy -import tf - -from derived_object_msgs.msg import ObjectArray, Object -from cav_msgs.msg import ExternalObjectList, ExternalObject - -external_objects_pub = rospy.Publisher('/environment/external_objects', ExternalObjectList, queue_size=1) -prev_objects = {} - -def converter(object): - """ - CARLA object message type: - derived_object_msgs::Object - """ - global prev_objects - object_type_lookup = {Object.CLASSIFICATION_PEDESTRIAN:ExternalObject.PEDESTRIAN, - Object.CLASSIFICATION_CAR:ExternalObject.SMALL_VEHICLE, - Object.CLASSIFICATION_TRUCK:ExternalObject.LARGE_VEHICLE, - Object.CLASSIFICATION_MOTORCYCLE:ExternalObject.MOTORCYCLE} - - ## CARMA external object init - object_msg = ExternalObject() - ## In the simulation source, the presence_vector should be a constant (except the object type) - object_msg.presence_vector = object_msg.presence_vector + \ - ExternalObject.ID_PRESENCE_VECTOR + \ - ExternalObject.POSE_PRESENCE_VECTOR + \ - ExternalObject.VELOCITY_PRESENCE_VECTOR + \ - ExternalObject.SIZE_PRESENCE_VECTOR + \ - ExternalObject.CONFIDENCE_PRESENCE_VECTOR + \ - ExternalObject.DYNAMIC_OBJ_PRESENCE + \ - ExternalObject.OBJECT_TYPE_PRESENCE_VECTOR - - object_msg.header = object.header - object_msg.id = object.id - object_msg.pose.pose = object.pose - - ## CARLA ROS Bridge will not provide the vehicle twist info which generated, - ## As a result, we need to calculate that based on position and time differences - if object.id in prev_objects: - ## time diff - curr_time = object.header.stamp.secs + 10**-9 * object.header.stamp.nsecs - prev_time = prev_objects[object.id]['object'].header.stamp.secs + 10**-9 * prev_objects[object.id]['object'].header.stamp.nsecs - time_diff = curr_time - prev_time - - if time_diff != 0: - ## dist diff - x_pose_diff = ((object.pose.position.x - prev_objects[object.id]['object'].pose.pose.position.x) ** 2) ** 0.5 - y_pose_diff = ((object.pose.position.y - prev_objects[object.id]['object'].pose.pose.position.y) ** 2) ** 0.5 - z_pose_diff = ((object.pose.position.z - prev_objects[object.id]['object'].pose.pose.position.z) ** 2) ** 0.5 - - object_msg.velocity.twist.linear.x = x_pose_diff / time_diff - object_msg.velocity.twist.linear.y = y_pose_diff / time_diff - object_msg.velocity.twist.linear.z = z_pose_diff / time_diff - else: - ## if time differences is 0, assign exact same velocity twist from previous object to current object - object_msg.velocity.twist.linear = prev_objects[object.id]['object'].velocity.twist.linear - - else: - prev_objects[object.id] = {} - - ## since we are using simulation, the external objects info is not received via detector. The confidence should always be 1 - object_msg.confidence = 1 - - ## object size convert - object_msg.size.x = object.shape.dimensions[0] - object_msg.size.y = object.shape.dimensions[1] - object_msg.size.z = object.shape.dimensions[2] - - ## the ros topic of /carla/{}/objects only provides dynamic object information. As a result, this parameter should always be 1. - object_msg.dynamic_obj = 1 - - - ## determine what object type is - if object.object_classified: - if object.classification in object_type_lookup: - object_msg.object_type = object_type_lookup[object.classification] - else: - object_msg.object_type = ExternalObject.UNKNOWN - else: - ## if the object classified is set as False, it means the object can not be identified - object_msg.presence_vector = object_msg.presence_vector - ExternalObject.OBJECT_TYPE_PRESENCE_VECTOR - - ## save the current object status - prev_objects[object.id]['object'] = object_msg - prev_objects[object.id]['update'] = True - prev_objects[object.id]["no_update_count"] = 0 - - return object_msg - -def external_objects_callback(obj_arr): - """ - callback current objects - obj_arr message type: - derived_object_msgs::ObjectArray - """ - global external_objects_pub - objects_msg = ExternalObjectList() - objects_msg.header = obj_arr.header - for i in range(len(obj_arr.objects)): - objects_msg.objects.append(converter(obj_arr.objects[i])) - - ## check the dictionary if object not being used anymore - remove_key_list = [] - for key in prev_objects: - if prev_objects[key]["update"]: - prev_objects[key]["update"] = False - else: - prev_objects[key]["no_update_count"] = prev_objects[key]["no_update_count"] + 1 - - if prev_objects[key]["no_update_count"] > 10: - remove_key_list.append(key) - ## remove these not use objects - for i in range(len(remove_key_list)): - prev_objects.pop(remove_key_list[i]) - - external_objects_pub.publish(objects_msg) - - -def convert_objects(): - """ - main loop - """ - rospy.init_node('carla_to_carma_external_objects', anonymous=True) - role_name = rospy.get_param('/role_name', 'ego_vehicle') - rospy.Subscriber('/carla/{}/objects'.format(role_name), ObjectArray, external_objects_callback) - rospy.spin() - - -if __name__ == '__main__': - print("carla_to_carma_external_objects") - convert_objects() diff --git a/carla-carma-integration/carla_carma_bridge/src/carla_carma_bridge/carla_to_carma_localization b/carla-carma-integration/carla_carma_bridge/src/carla_carma_bridge/carla_to_carma_localization deleted file mode 100755 index 794d5592..00000000 --- a/carla-carma-integration/carla_carma_bridge/src/carla_carma_bridge/carla_to_carma_localization +++ /dev/null @@ -1,77 +0,0 @@ -#!/usr/bin/env python -# Copyright (C) 2021 LEIDOS. -# -# 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 file is loosely based on the reference architecture developed by Intel Corporation for Leidos located here -# https://github.com/41623134/carla-autoware/blob/master/catkin_ws/src/carla_autoware_bridge/src/carla_autoware_bridge/odometry_to_posestamped -# -# That file has the following license and some code snippets from it may be present in this file as well and are under the same license. -# -# Copyright (c) 2018-2019 Intel Corporation -# -# This work is licensed under the terms of the MIT license. -# For a copy, see . -# -""" -Subscribe from CARLA :nav_msgs::Odometry - Topic: /carla/{}/odometry - -Publish to CARMA :geometry_msgs::PoseStamped - Topic: /localization/gnss_pose; - /localization/current_pose - /hardware_interface/vehicle/twist -""" -import rospy -from geometry_msgs.msg import PoseStamped, TwistStamped -from nav_msgs.msg import Odometry - -gnss_pub = rospy.Publisher('/localization/gnss_pose', PoseStamped, queue_size=10) -pose_pub = rospy.Publisher('/localization/current_pose', PoseStamped, queue_size=10) -twist_pub = rospy.Publisher('/hardware_interface/vehicle/twist', TwistStamped, queue_size=10) - -def odometry_callback(carla_odometry): - """ - callback odometry - carla_odometry message type: - nav_msgs::Odometry - """ - global pose_pub, twist_pub, gnss_pub - header = carla_odometry.header - twist = TwistStamped() - twist.header = header - twist.twist.linear = carla_odometry.twist.twist.linear - twist.twist.angular = carla_odometry.twist.twist.angular - - pose = PoseStamped() - pose.header = header - pose.pose = carla_odometry.pose.pose - pose_pub.publish(pose) - gnss_pub.publish(pose) - twist_pub.publish(twist) - - -def convert_odometry(): - """ - main loop - """ - rospy.init_node('carla_to_carma_localization', anonymous=True) - role_name = rospy.get_param('~role_name', 'ego_vehicle') - rospy.Subscriber('/carla/{}/odometry'.format(role_name), Odometry, odometry_callback, queue_size=10) - rospy.spin() - - -if __name__ == '__main__': - print("carla_to_carma_localization") - convert_odometry() diff --git a/carla-carma-integration/carla_carma_bridge/src/carla_carma_bridge/carla_to_carma_vehicle_status b/carla-carma-integration/carla_carma_bridge/src/carla_carma_bridge/carla_to_carma_vehicle_status deleted file mode 100755 index b9dd540b..00000000 --- a/carla-carma-integration/carla_carma_bridge/src/carla_carma_bridge/carla_to_carma_vehicle_status +++ /dev/null @@ -1,119 +0,0 @@ -#!/usr/bin/env python -# Copyright (C) 2021 LEIDOS. -# -# 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 file is loosely based on the reference architecture developed by Intel Corporation for Leidos located here -# https://github.com/41623134/carla-autoware/blob/master/catkin_ws/src/carla_autoware_bridge/src/carla_autoware_bridge/carla_to_autoware_vehicle_status -# -# That file has the following license and some code snippets from it may be present in this file as well and are under the same license. -# -# Copyright (c) 2019 Intel Corporation -# -# This work is licensed under the terms of the MIT license. -# For a copy, see . -# - -""" -Subscribe from CARLA :carla_msgs::CarlaEgoVehicleStatus - Topic: /carla/{}/vehicle_status - -Subscribe from CARLA :carla_msgs::CarlaEgoVehicleInfo - Topic: /carla/{}/vehicle_info - -Publish to CARMA :autoware_msgs::VehicleStatus - Topic: /hardware_interface/vehicle_status - -""" -import math -import rospy -from carla_msgs.msg import CarlaEgoVehicleInfo -from carla_msgs.msg import CarlaEgoVehicleStatus -from autoware_msgs.msg import VehicleStatus, Gear - -vehicle_status_pub = rospy.Publisher('/hardware_interface/vehicle_status', VehicleStatus, queue_size=1) -vehicle_info = None - -max_steering_angle = rospy.get_param('~max_steering_degree', 70) - -def vehicle_info_callback(vehicle_info_msg): - """ - callback for vehicle info - vehicle_info_msg type: - carla_msgs::CarlaEgoVehicleInfo - """ - global vehicle_info - vehicle_info = vehicle_info_msg - -def vehicle_status_callback(vehicle_status_msg): - """ - callback for vehicle status - vehicle_status_msg type: - carla_msgs::CarlaEgoVehicleStatus - """ - global vehicle_status_pub - if vehicle_info is None: - return - - status = VehicleStatus() - status.header = vehicle_status_msg.header - - # calculate max steering angle - global max_steering_angle - max_steering_angle = math.radians(max_steering_angle) - - # get max steering angle (use smallest non-zero value of all wheels) - for wheel in vehicle_info.wheels: - if wheel.max_steer_angle and wheel.max_steer_angle < max_steering_angle: - max_steering_angle = wheel.max_steer_angle - - status.angle = vehicle_status_msg.control.steer * math.degrees(max_steering_angle) - status.speed = vehicle_status_msg.velocity - - # VehicleStatus from autoware_msgs has different parameter compare with autoware 1.12 and 1.14 - if vehicle_status_msg.control.reverse: - try: - status.gearshift = Gear.REVERSE - except: - status.current_gear.gear = Gear.REVERSE - else: - try: - status.gearshift = Gear.DRIVE - except: - status.current_gear.gear = Gear.DRIVE - - if vehicle_status_msg.control.manual_gear_shift: - status.drivemode = VehicleStatus.MODE_MANUAL - else: - status.drivemode = VehicleStatus.MODE_AUTO - vehicle_status_pub.publish(status) - - -def convert_status_carla_to_carma(): - """ - main loop - """ - - rospy.init_node('convert_status_carla_to_autoware', anonymous=True) - role_name = rospy.get_param('~role_name', 'ego_vehicle') - rospy.Subscriber('/carla/{}/vehicle_status'.format(role_name), CarlaEgoVehicleStatus, - vehicle_status_callback) - rospy.Subscriber('/carla/{}/vehicle_info'.format(role_name), CarlaEgoVehicleInfo, - vehicle_info_callback) - rospy.spin() - - -if __name__ == '__main__': - print("carla_to_carma_vehicle_status") - convert_status_carla_to_carma() diff --git a/carla-carma-integration/carla_carma_bridge/src/carla_carma_bridge/carma_carla_driver_status b/carla-carma-integration/carla_carma_bridge/src/carla_carma_bridge/carma_carla_driver_status deleted file mode 100755 index e8483d3e..00000000 --- a/carla-carma-integration/carla_carma_bridge/src/carla_carma_bridge/carma_carla_driver_status +++ /dev/null @@ -1,77 +0,0 @@ -#!/usr/bin/env python -# Copyright (C) 2021 LEIDOS. -# -# 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. - - -""" -Publish to CARMA :cav_msgs::DriverStatus - Topic: /hardware_interface/driver_discovery; -""" -import rospy -from cav_msgs.msg import DriverStatus - -driver_status_pub = rospy.Publisher('/hardware_interface/driver_discovery', DriverStatus, queue_size=10) - -def driver_status(): - """ - main loop - """ - rospy.init_node('carma_carla_driver_status', anonymous=True) - pub_rate = rospy.get_param('~driver_status_pub_rate', 10) - rate = rospy.Rate(pub_rate) - - ## initial msg parameters - lidar_enabled = rospy.get_param('~lidar_enabled', True) - controller_enabled = rospy.get_param('~controller_enabled', True) - camera_enabled = rospy.get_param('~camera_enabled', True) - gnss_enabled = rospy.get_param('~gnss_enabled', True) - - while not rospy.is_shutdown(): - - ## SSC - driver_status_msg = DriverStatus() - driver_status_msg.name = '/hardware_interface/carla_driver' - driver_status_msg.status = DriverStatus.OPERATIONAL - driver_status_msg.lidar = lidar_enabled - driver_status_msg.controller = controller_enabled - driver_status_msg.camera = camera_enabled - driver_status_msg.gnss = gnss_enabled - - ## camera driver - camera_driver_status_msg = DriverStatus() - camera_driver_status_msg.name = '/hardware_interface/carla_camera_driver' - camera_driver_status_msg.status = DriverStatus.OPERATIONAL - camera_driver_status_msg.camera = camera_enabled - - ## lidar driver - lidar_driver_status_msg = DriverStatus() - lidar_driver_status_msg.name = '/hardware_interface/carla_lidar_driver' - lidar_driver_status_msg.status = DriverStatus.OPERATIONAL - lidar_driver_status_msg.lidar = lidar_enabled - - ## gnss driver - gnss_driver_status_msg = DriverStatus() - gnss_driver_status_msg.name = '/hardware_interface/carla_gnss_driver' - gnss_driver_status_msg.status = DriverStatus.OPERATIONAL - gnss_driver_status_msg.gnss = gnss_enabled - - driver_status_pub.publish(driver_status_msg) - driver_status_pub.publish(camera_driver_status_msg) - driver_status_pub.publish(lidar_driver_status_msg) - driver_status_pub.publish(gnss_driver_status_msg) - rate.sleep() - -if __name__ == '__main__': - print("carma_carla_driver_status") - driver_status() diff --git a/carla-carma-integration/carla_carma_bridge/src/carla_carma_bridge/carma_carla_robot_status b/carla-carma-integration/carla_carma_bridge/src/carla_carma_bridge/carma_carla_robot_status deleted file mode 100755 index 4c72d49b..00000000 --- a/carla-carma-integration/carla_carma_bridge/src/carla_carma_bridge/carma_carla_robot_status +++ /dev/null @@ -1,60 +0,0 @@ -#!/usr/bin/env python -# Copyright (C) 2021 LEIDOS. -# -# 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. - - -""" -Publish to CARMA :cav_msgs::RobotEnabled - Topic: /hardware_interface/controller/robot_status - -Subscribe from CARMA :cav_msgs::GuidanceState - Topic: /guidance/state -""" -import rospy -from cav_msgs.msg import RobotEnabled, GuidanceState - -robot_status_pub = rospy.Publisher('/hardware_interface/controller/robot_status', RobotEnabled, queue_size=10) -robot_status_msg = RobotEnabled() - -def guidance_state_callback(guidance_state_msg): - """ - callback for guidance state subscribing from CARMA - guidance_state_msg type: - cav_msgs::GuidanceState - """ - global robot_status_msg - - if guidance_state_msg.state == GuidanceState.ENGAGED or guidance_state_msg.state == GuidanceState.ACTIVE: - robot_status_msg.robot_active = True - else: - robot_status_msg.robot_active = False - -def robot_status(): - """ - main loop - """ - rospy.init_node('carma_carla_robot_status', anonymous=True) - pub_rate = rospy.get_param('~robot_status_pub_rate', 10) - rate = rospy.Rate(pub_rate) - - rospy.Subscriber('/guidance/state', GuidanceState, guidance_state_callback, queue_size=1) - robot_status_msg.robot_enabled = True - - while not rospy.is_shutdown(): - robot_status_pub.publish(robot_status_msg) - rate.sleep() - -if __name__ == '__main__': - print("carma_carla_robot_status") - robot_status() diff --git a/carla-carma-integration/carla_carma_bridge/src/carla_carma_bridge/carma_to_carla_ackermann_cmd b/carla-carma-integration/carla_carma_bridge/src/carla_carma_bridge/carma_to_carla_ackermann_cmd deleted file mode 100755 index 89122c0c..00000000 --- a/carla-carma-integration/carla_carma_bridge/src/carla_carma_bridge/carma_to_carla_ackermann_cmd +++ /dev/null @@ -1,120 +0,0 @@ -#!/usr/bin/env python -# Copyright (C) 2021 LEIDOS. -# -# 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 file is loosely based on the reference architecture developed by Intel Corporation for Leidos located here -# https://github.com/41623134/carla-autoware/blob/master/catkin_ws/src/carla_autoware_bridge/src/carla_autoware_bridge/vehiclecmd_to_ackermanndrive -# -# That file has the following license and some code snippets from it may be present in this file as well and are under the same license. -# -# Copyright (c) 2019 Intel Corporation -# -# This work is licensed under the terms of the MIT license. -# For a copy, see . -# - -""" -Subscribe from CARMA :autoware_msgs::VehicleCmd - Topic: /hardware_interface/vehicle_cmd - -Subscribe from CARMA :std_msgs::Float32 - Topic: /guidance/twist_filter/result/twist/lateral_jerk - -Subscribe from CARMA :cav_msgs::GuidanceState - Topic: /guidance/state - -Publish to CARLA :ackermann_msgs::AckermannDrive - Topic: /carla/{}/ackermann_cmd - -""" -import rospy -from ackermann_msgs.msg import AckermannDrive -from autoware_msgs.msg import VehicleCmd -from cav_msgs.msg import GuidanceState -from std_msgs.msg import Float32 - -ackermann_cmd_pub = None -guidance_state = GuidanceState.STARTUP -init_status = True -init_cmd = AckermannDrive() -lateral_jerk = 0 - -def guidance_state_callback(guidance_state_msg): - """ - callback for guidance state subscribing from CARMA - guidance_state_msg type: - cav_msgs::GuidanceState - """ - global init_status, guidance_state, init_cmd, ackermann_cmd_pub - - guidance_state = guidance_state_msg.state - if guidance_state == GuidanceState.ENGAGED and init_status: - init_status = False - ## providing initial ackermann command to carla virtual vehicle - init_cmd.speed = rospy.get_param('~init_speed', 10) - init_cmd.acceleration = rospy.get_param('~init_acceleration', 1) - init_cmd.steering_angle = rospy.get_param('~init_steering_angle', 0) - init_cmd.jerk = rospy.get_param('~init_jerk', 0) - ackermann_cmd_pub.publish(init_cmd) - -def commanded_jerk_callback(lateral_jerk_msg): - """ - callback for commanded jerk from CARMA - lateral_jerk_msg type: - std_msgs::Float32 - """ - - global lateral_jerk - lateral_jerk = lateral_jerk_msg.data - -def vehicle_cmd_callback(vehicle_cmd): - """ - callback for vehicle cmds subscribing from CARMA - vehicle_cmd type: - autoware_msgs::VehicleCmd - """ - global ackermann_cmd_pub - if guidance_state != GuidanceState.ENGAGED: - return - else: - ackermann_drive = AckermannDrive() - ackermann_drive.speed = vehicle_cmd.ctrl_cmd.linear_velocity - ackermann_drive.acceleration = vehicle_cmd.ctrl_cmd.linear_acceleration - ackermann_drive.steering_angle = vehicle_cmd.ctrl_cmd.steering_angle - ackermann_drive.jerk = lateral_jerk - - ## publishing ackermann drive msg to CARLA virtual vehicle - ackermann_cmd_pub.publish(ackermann_drive) - - -def vehicle_cmd_to_ackermanndrive(): - """ - mainloop - """ - global ackermann_cmd_pub - rospy.init_node('carma_to_carla_vehicle_cmd') - role_name = rospy.get_param('~role_name', 'ego_vehicle') - # pub init - ackermann_cmd_pub = rospy.Publisher('/carla/{}/ackermann_cmd'.format(role_name), AckermannDrive, queue_size=1) - # sub init - rospy.Subscriber('/hardware_interface/vehicle_cmd', VehicleCmd, vehicle_cmd_callback, queue_size=1) - rospy.Subscriber('/guidance/state', GuidanceState, guidance_state_callback, queue_size=1) - rospy.Subscriber('/guidance/twist_filter/result/twist/lateral_jerk', Float32, commanded_jerk_callback, queue_size=1) - rospy.spin() - - -if __name__ == '__main__': - print("carma_to_carla_vehicle_cmd") - vehicle_cmd_to_ackermanndrive() diff --git a/carla-carma-integration/docs/images/CARMA-Web-UI.png b/carla-carma-integration/docs/images/CARMA-Web-UI.png deleted file mode 100644 index 3d20cfbd..00000000 Binary files a/carla-carma-integration/docs/images/CARMA-Web-UI.png and /dev/null differ diff --git a/carla-carma-integration/run.sh b/carla-carma-integration/run.sh deleted file mode 100755 index 0b632c8f..00000000 --- a/carla-carma-integration/run.sh +++ /dev/null @@ -1,14 +0,0 @@ -#!/bin/bash - -RUNTIME="" -DOCKER_VERSION=$(docker version --format '{{.Client.Version}}' | cut --delimiter=. --fields=1,2) -if [[ $DOCKER_VERSION < "19.03" ]] && ! type nvidia-docker; then - RUNTIME="--gpus all" -else - RUNTIME="--runtime=nvidia" -fi -docker run \ - -it --rm\ - --name carla_carma_integration \ - --net=host \ - usdotfhwastol/carla-carma-integration:latest diff --git a/co-simulation/carla-sumo-mosaic-22.1-SNAPSHOT.zip b/co-simulation/doc/gif/carla_sumo_mosaic_demo.gif similarity index 66% rename from co-simulation/carla-sumo-mosaic-22.1-SNAPSHOT.zip rename to co-simulation/doc/gif/carla_sumo_mosaic_demo.gif index 1bf981f1..875e82c1 100644 Binary files a/co-simulation/carla-sumo-mosaic-22.1-SNAPSHOT.zip and b/co-simulation/doc/gif/carla_sumo_mosaic_demo.gif differ diff --git a/co-simulation/doc/gif/ready.gif b/co-simulation/doc/gif/ready.gif new file mode 100644 index 00000000..4e9ebc79 Binary files /dev/null and b/co-simulation/doc/gif/ready.gif differ diff --git a/co-simulation/docker/ns3-docker/Dockerfile b/co-simulation/docker/ns3-docker/Dockerfile deleted file mode 100644 index cf09e1bb..00000000 --- a/co-simulation/docker/ns3-docker/Dockerfile +++ /dev/null @@ -1,123 +0,0 @@ -FROM ubuntu:18.04 - -MAINTAINER ODU Team -LABEL Description="Dockerised Simulation of Carla_Sumo_Mosaic" - -ENV SUMO_HOME /usr/share/sumo -ENV SUMO_USER carla_sumo_mosaic - - -ENV CARLA_HOME /CARLA_0.9.10/ -RUN export CARLA_HOME - -RUN apt-get update && \ - apt-get install -y openjdk-8-jdk && \ - apt-get install -y ant && \ - apt-get clean && \ - rm -rf /var/lib/apt/lists/ && \ - rm -rf /var/cache/oracle-jdk8-installer; - -ENV JAVA_HOME /usr/lib/jvm/java-8-openjdk-amd64/ -RUN export JAVA_HOME - -RUN apt-get -y update - -RUN apt-get install x11-xserver-utils dconf-editor dbus-x11 -y - -RUN apt-get update && apt-get upgrade -y && apt-get clean - -# Python package management and basic dependencies -RUN apt-get install -y curl python3.7 python3.7-dev python3.7-distutils - -# Register the version in alternatives -RUN update-alternatives --install /usr/bin/python python /usr/bin/python3.7 1 - -# Set python 3 as the default python -RUN update-alternatives --set python /usr/bin/python3.7 - -RUN curl -s https://bootstrap.pypa.io/get-pip.py -o get-pip.py && \ - python get-pip.py --force-reinstall && \ - rm get-pip.py - -RUN pip3.7 install lxml - -# Dependencies for glvnd and X11. -RUN apt-get update \ - && apt-get install -y -qq --no-install-recommends \ - libglvnd0 \ - libgl1 \ - libglx0 \ - libegl1 \ - libxext6 \ - libx11-6 \ - && rm -rf /var/lib/apt/lists/* - -# Env vars for the nvidia-container-runtime. -ENV NVIDIA_VISIBLE_DEVICES all -ENV NVIDIA_DRIVER_CAPABILITIES graphics,utility,compute - -RUN apt-get update && \ - apt-get install -y software-properties-common && \ - rm -rf /var/lib/apt/lists/* - -# Install python3.6 for NS-3 installation -RUN add-apt-repository ppa:deadsnakes/ppa && \ - apt update && \ - apt install python3.6 - -# Install other dependencies -RUN apt-get update && \ - apt-get install -y g++ gcc unzip tar python3-dev && \ - apt-get install -y autoconf automake libtool curl make && \ - apt-get install -y libxml2 libsqlite3-dev && \ - apt-get install -y libxml2-dev - -RUN \ - apt-get update && \ - apt-get install -y --allow-unauthenticated \ - build-essential \ - pkg-config \ - lbzip2 \ - libprotobuf-dev \ - libsqlite3-dev \ - protobuf-compiler \ - patch \ - rsync \ - wget - -# Install vim as text editor -RUN apt-get install -y vim - -RUN apt-get install -y xterm - -RUN apt install -y default-jdk - -# Install SUMO -RUN add-apt-repository ppa:sumo/stable - -RUN apt-get update - -RUN apt-get install -y \ - sumo \ - sumo-tools \ - sumo-doc - -RUN adduser $SUMO_USER --disabled-password - -# Enable sudo -RUN apt-get update && apt-get install -y sudo - -RUN adduser $SUMO_USER sudo --disabled-password - -RUN echo '%sudo ALL=(ALL) NOPASSWD:ALL' >> \ -/etc/sudoers - - -### Docker (Optional) ### -# RUN apt-get update && \ -# apt-get -qy full-upgrade && \ -# apt-get install -qy curl && \ -# apt-get install -qy curl && \ -# curl -sSL https://get.docker.com/ | sh - -# RUN adduser $SUMO_USER docker --disabled-password diff --git a/co-simulation/docker/ns3-docker/README.md b/co-simulation/docker/ns3-docker/README.md deleted file mode 100644 index 9d957771..00000000 --- a/co-simulation/docker/ns3-docker/README.md +++ /dev/null @@ -1,229 +0,0 @@ -# Running CARLA-SUMO-MOSAIC Co-Simulation Tool with NS-3 Integration in Docker - -This is the tutorial to run CARLA-SUMO-MOSAIC co-simulation tool in a docker container. It is recommended to run the co-simulation tool on a **high-performance** computer. - -## Test Platform - -- Operating System: Ubuntu 20.04.2 LTS -- CPU: Intel(R) Core(TM) i7-9700K CPU @ 3.60 GHz -- RAM: 16 GB -- Graphics: NVIDIA GeForce RTX 2070 Super 8 GB - -## Prerequisites - -- NVIDIA GPU with at least 8 GB -- NVIDIA drivers > 361.93 -- Free Disk Space > 30 GB -- NVIDIA Container Toolkit -- Docker - -If you do not have Docker installed, please refer to this [link](https://docs.docker.com/engine/install/ubuntu/) for installation. - -If you do not have NVIDIA Container Toolkit installed, please refer to this [link](https://docs.nvidia.com/datacenter/cloud-native/container-toolkit/install-guide.html) for installation. - -## Build Docker Image of Co-simulation Tool - -#### Preparation for building docker image - -- Download the executable bundle file `carla-sumo-mosaic-21.2.zip` from GitHub and extract the zip file, the folder named `carla-sumo-mosaic-21.2` will be generated and rename the folder as `ns-3-integration`. -- Put the docker file (Dockerfile), the folder of CARLA executable file (CARLA_0.9.10), and the folder of `ns-3-integration`in the same folder. -- Change the CARLA path in the CARLA configuration file of scenarios to the location of the CARLA executable file. -- The .sh files (CarlaUE4.sh and bridge.sh) must be given permission. - -#### Build docker image - -##### Step 1: Run the following command to build the docker image - -``` -docker build - < Dockerfile -t usdotfhwastol/carma-xil-cosimulation -``` -##### Step 2: Run docker image with a docker container -``` -docker run --rm -it --gpus all --net=host -v /tmp/.X11-unix:/tmp/.X11-unix -e DISPLAY=$DISPLAY -e QT_X11_NO_MITSHM=1 --user=carla_sumo_mosaic usdotfhwastol/carma-xil-cosimulation -``` -##### Step 3: Copy CARLA and Co-Simulation tool with NS-3 to the docker image and commit them - - -Copy `CARLA_0.9.10` and `ns-3-integration` folder into this container. - -``` -docker cp CARLA_0.9.10 :./ -docker cp ns-3-integration :./ -``` -##### Step 4: Upzip scenarios from Co-simulation Scenarios.zip under co-simulation tool folder and copy to docker -``` -docker cp Town04_10 :./ns-3-integration/scenarios -docker cp Town04_200 :./ns-3-integration/scenarios -``` - -### Modify files in Docker Container - -#### Step 1: Modify `ns3_installer.sh` - -In Docker container, type: - -``` -cd ns-3-integration/bin/fed/ns3 -``` - -Then modify `ns3_installer.sh` by: - -``` -vim ns3_installer.sh -``` - -(If you see a message `vim: command not found`, please use `sudo apt-get install vim` to install vim as text editor) - -In the `build_ns3()` function, after `CXXFLAGS="-Wno-error" python3.6 ./build.py --disable-netanim`, add the following command - -``` -sudo cp -ar ns-3.28/build/ns3 /usr/include/ -``` - -#### Step 2: Build NS-3 - -In directory `ns-3-integration/bin/fed/ns3`, type: - -``` -./ns3_installer.sh -``` - -Once all 1947 files are compiled and a successful message shows up, it means NS-3 is successful installed. - -#### Step 3: Add NS-3 as environment variable - -``` -export NS3_HOME='/ns-3-integration/bin/fed/ns3' -``` - -Use `printenv` to check if NS-3 is successful added to environment variable. - -#### Step 4: Modify `run.sh` - -In directory `ns-3-integration/bin/fed/ns3`, type: - -``` -vim run.sh -``` - -Change line 11 to: - -``` -LD_LIBRARY_PATH=/ns-3-integration/bin/fed/ns3/ns-allinone-3.28/ns-3.28/build /ns-3-integration/bin/fed/ns3/ns-allinone-3.28/ns-3.28/build/scratch/mosaic_starter --port=$port --cmdPort=$cmdport --configFile=scratch/ns3_federate_config.xml -``` - -Now, you can test if NS-3 works. - -In root directory, type: - -``` -cd /ns-3-integration -``` -Change mosaic.sh permission by typing command: - -``` -chmod +x mosaic.sh -``` - -Use example `Tiergarten` to test: - -``` -./mosaic.sh -s Tiergarten -``` - -#### Step 5: Modify traci library (For Co-Simulation) - -In root directory, type: - -``` -cd /usr/share/sumo/tools/traci -``` - -Then in the directory `/usr/share/sumo/tools/traci`, modify the following three files: - -1. `constants.py` - - ``` - sudo nano constants.py - ``` - - Add these to `constants.py`: - - ```python - # command: get V2X message - CMD_GET_V2X = 0x0d - - # command: set V2X message - CMD_SET_V2X = 0x2f - ``` - -2. `main.py` - - ``` - sudo nano main.py - ``` - - Add these methods to `main.py`: - - ```python - def getV2xMessage(): - if "" not in _connections: - raise FatalTraCIError("Not connected.") - return _connections[""].getV2xMessage() - - def setV2xMessage(message): - if "" not in _connections: - raise FatalTraCIError("Not connected.") - return _connections[""].setV2xMessage(message) - ``` - -3. `connection.py` - - ``` - sudo nano connection.py - ``` - - Add the following commands: - - ```python - def getV2xMessage(self): - command = tc.CMD_GET_V2X - result = self._sendCmd(command,None,None) - result.readLength() - response = result.read("!B")[0] - - if response != command: - raise FatalTraCIError("Received answer %s for command %s." % (response, command)) - return result.readStringList() - - def setV2xMessage(self, message): - self._sendCmd(tc.CMD_SET_V2X, None, None, "s", message) - ``` -#### Step 6: Modify `carla_config.json` - -Modify carla_config.json file as following under folder /ns-3-integration/scenarios//carla/: - -``` -{ - "updateInterval": 100, - "carlaUE4Path": "./CARLA_0.9.10/", - "bridgePath": "./scenarios//carla; bridge.sh", - "carlaConnectionPort": 8913 -} -``` - -### Run Co-simulation - -Once everything is ready, under directory `/ns-3-integration`, simply type: - -``` -./mosaic.sh -s Town04_10 -./mosaic.sh -s Town04_200 -``` - -After the run if there is no issue, commit docker container to docker image -``` -docker container commit usdotfhwastol/carma-xil-cosimulation -``` - -Current CARMA XIL Version has a known issue with a port conflict between NS-3 and CARMA-CARLA integration see [#39](https://github.com/usdot-fhwa-stol/carma-simulation/issues/39). The recommended workaround is to run exclusively one or the other module. To run with only NS-3module run **`./mosaic.sh -s Co-simulation`**. diff --git a/co-simulation/fed/mosaic-carla/src/main/java/org/eclipse/mosaic/fed/carla/ambassador/CarlaAmbassador.java b/co-simulation/fed/mosaic-carla/src/main/java/org/eclipse/mosaic/fed/carla/ambassador/CarlaAmbassador.java index 9cd57af2..75be4598 100644 --- a/co-simulation/fed/mosaic-carla/src/main/java/org/eclipse/mosaic/fed/carla/ambassador/CarlaAmbassador.java +++ b/co-simulation/fed/mosaic-carla/src/main/java/org/eclipse/mosaic/fed/carla/ambassador/CarlaAmbassador.java @@ -92,6 +92,11 @@ public class CarlaAmbassador extends AbstractFederateAmbassador { */ private int connectionAttempts = 5; + /** + * Maximum amount of attempts to connect to CARLA simulator. + */ + private int executedTimes = 0; + /** * Carla simulator client port */ @@ -158,19 +163,20 @@ public FederateExecutor createFederateExecutor(String host, int port, CLocalHost /** * Get CARLA simulator executable file location - * + * * @param executable the name of carla executable file * @return the path to CarlaUE4 executable file */ String getCarlaExecutable(String executable) { String carlaHome = null; - if (System.getenv("CARLA_HOME") != null) { - carlaHome = System.getenv("CARLA_HOME"); - log.info("use carla path from environmental variable: " + carlaHome); - } else if (carlaConfig.carlaUE4Path != null) { + if (carlaConfig.carlaUE4Path != null) { carlaHome = carlaConfig.carlaUE4Path; log.info("use carla path from configuration file: " + carlaHome); } + else if (System.getenv("CARLA_HOME") != null) { + carlaHome = System.getenv("CARLA_HOME"); + log.info("use carla path from environmental variable: " + carlaHome); + } if (StringUtils.isNotBlank(carlaHome)) { boolean isWindows = System.getProperty("os.name").toLowerCase().startsWith("windows"); if (isWindows) { @@ -186,7 +192,7 @@ String getCarlaExecutable(String executable) { /** * This method is called to tell the federate the start time and the end time. * It is also used to start CARLA, and connect to CARLA. - * + * * @param startTime Start time of the simulation run in nano seconds. * @param endTime End time of the simulation run in nano seconds. * @throws InternalFederateException Exception is thrown if an error is occurred @@ -335,8 +341,8 @@ public synchronized void processTimeAdvanceGrant(long time) throws InternalFeder nextTimeStep += carlaConfig.updateInterval * TIME.MILLI_SECOND; isSimulationStep = false; } - rti.requestAdvanceTime(nextTimeStep, 0, (byte) 2); - + rti.requestAdvanceTime(nextTimeStep + this.executedTimes, 0, (byte) 2); + this.executedTimes++; } catch (IllegalValueException e) { log.error("Error during advanceTime(" + time + ")", e); throw new InternalFederateException(e); @@ -378,7 +384,7 @@ public void finishSimulation() throws InternalFederateException { /** * get the CARLA command arguments - * + * * @param port CARLA simulator client port * @return the list of CARLA command arguments */ @@ -417,7 +423,7 @@ public boolean isTimeRegulating() { /** * Trigger a new CarlaTraciRequest, SimulationStep or ExternalMessage * interaction - * + * * @param length command length * @param command command */ @@ -476,7 +482,7 @@ public void processInteraction(Interaction interaction) { /** * process the Carla traci response interaction - * + * * @param interaction Carla Traci Response interaction */ private void receiveInteraction(CarlaTraciResponse interaction) { @@ -492,7 +498,7 @@ private void receiveInteraction(CarlaTraciResponse interaction) { /** * process the traci response interaction - * + * * @param interaction Simulation Step Response interaction */ private void receiveInteraction(SimulationStepResponse interaction) { @@ -500,6 +506,7 @@ private void receiveInteraction(SimulationStepResponse interaction) { if (carlaConnection.getDataOutputStream() != null) { carlaConnection.getDataOutputStream().write(interaction.getResult()); + this.executedTimes = 0; } } catch (Exception e) { @@ -509,7 +516,7 @@ private void receiveInteraction(SimulationStepResponse interaction) { /** * Process the CARLA vehicles receiving V2X message interaction - * + * * @param interaction CarlaV2xMessageReception interaction */ private void receiveInteraction(CarlaV2xMessageReception interaction) { @@ -567,7 +574,7 @@ private void sendReceivedV2xMessageToCarla() { /** * Process the received messages from CARLA simulator. - * + * * @param length the length of command * @param command received command * @return received external message @@ -591,4 +598,4 @@ private String[] processReceivedV2xMessageFromCarla(int length, byte[] command) } return message.split(";"); } -} \ No newline at end of file +} diff --git a/co-simulation/traci_update/connection.py b/co-simulation/traci_update/connection.py new file mode 100644 index 00000000..a8dcec77 --- /dev/null +++ b/co-simulation/traci_update/connection.py @@ -0,0 +1,435 @@ +# -*- coding: utf-8 -*- +# Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo +# Copyright (C) 2008-2022 German Aerospace Center (DLR) and others. +# This program and the accompanying materials are made available under the +# terms of the Eclipse Public License 2.0 which is available at +# https://www.eclipse.org/legal/epl-2.0/ +# This Source Code may also be made available under the following Secondary +# Licenses when the conditions for such availability set forth in the Eclipse +# Public License 2.0 are satisfied: GNU General Public License, version 2 +# or later which is available at +# https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html +# SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later + +# @file connection.py +# @author Michael Behrisch +# @author Lena Kalleske +# @author Mario Krumnow +# @author Daniel Krajzewicz +# @author Jakob Erdmann +# @date 2008-10-09 + +from __future__ import print_function +from __future__ import absolute_import +import socket +import struct +import sys +import warnings +import abc + +from . import constants as tc +from .exceptions import TraCIException, FatalTraCIError +from .domain import _defaultDomains +from .storage import Storage + +_RESULTS = {0x00: "OK", 0x01: "Not implemented", 0xFF: "Error"} + + +class Connection: + + """Contains the socket, the composed message string + together with a list of TraCI commands which are inside. + """ + + def __init__(self, host, port, process): + if sys.platform.startswith('java'): + # working around jython 2.7.0 bug #2273 + self._socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP) + else: + self._socket = socket.socket() + self._socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) + self._socket.connect((host, port)) + self._process = process + self._string = bytes() + self._queue = [] + self._subscriptionMapping = {} + self._stepListeners = {} + self._nextStepListenerID = 0 + self._traceFile = None + for domain in _defaultDomains: + domain._register(self, self._subscriptionMapping) + + def _recvExact(self): + try: + result = bytes() + while len(result) < 4: + t = self._socket.recv(4 - len(result)) + if not t: + return None + result += t + length = struct.unpack("!i", result)[0] - 4 + result = bytes() + while len(result) < length: + t = self._socket.recv(length - len(result)) + if not t: + return None + result += t + return Storage(result) + except socket.error: + return None + + def _sendExact(self): + if self._socket is None: + raise FatalTraCIError("Connection already closed.") + length = struct.pack("!i", len(self._string) + 4) + # print("python_sendExact: '%s'" % ' '.join(map(lambda x : "%X" % ord(x), self._string))) + self._socket.send(length + self._string) + result = self._recvExact() + if not result: + self._socket.close() + del self._socket + raise FatalTraCIError("connection closed by SUMO") + for command in self._queue: + prefix = result.read("!BBB") + err = result.readString() + if prefix[2] or err: + self._string = bytes() + self._queue = [] + raise TraCIException(err, prefix[1], _RESULTS[prefix[2]]) + elif prefix[1] != command: + raise FatalTraCIError("Received answer %s for command %s." % (prefix[1], command)) + elif prefix[1] == tc.CMD_STOP: + length = result.read("!B")[0] - 1 + result.read("!%sx" % length) + self._string = bytes() + self._queue = [] + return result + + def _pack(self, format, *values): + packed = bytes() + for f, v in zip(format, values): + if f == "i": + packed += struct.pack("!Bi", tc.TYPE_INTEGER, int(v)) + elif f == "I": # raw int for setOrder + packed += struct.pack("!i", int(v)) + elif f == "d": + packed += struct.pack("!Bd", tc.TYPE_DOUBLE, float(v)) + elif f == "D": # raw double for some base commands like simstep + packed += struct.pack("!d", float(v)) + elif f == "b": + packed += struct.pack("!Bb", tc.TYPE_BYTE, int(v)) + elif f == "B": + packed += struct.pack("!BB", tc.TYPE_UBYTE, int(v)) + elif f == "u": # raw unsigned byte needed for distance command and subscribe + packed += struct.pack("!B", int(v)) + elif f == "s": + v = str(v) + packed += struct.pack("!Bi", tc.TYPE_STRING, len(v)) + v.encode("latin1") + elif f == "p": # polygon + if len(v) <= 255: + packed += struct.pack("!BB", tc.TYPE_POLYGON, len(v)) + else: + packed += struct.pack("!BBi", tc.TYPE_POLYGON, 0, len(v)) + for p in v: + packed += struct.pack("!dd", *p) + elif f == "t": # tuple aka compound + packed += struct.pack("!Bi", tc.TYPE_COMPOUND, v) + elif f == "c": # color + packed += struct.pack("!BBBBB", tc.TYPE_COLOR, int(v[0]), int(v[1]), int(v[2]), + int(v[3]) if len(v) > 3 else 255) + elif f == "l": # string list + packed += struct.pack("!Bi", tc.TYPE_STRINGLIST, len(v)) + for s in v: + packed += struct.pack("!i", len(s)) + s.encode("latin1") + elif f == "f": # float list + packed += struct.pack("!Bi", tc.TYPE_DOUBLELIST, len(v)) + for x in v: + packed += struct.pack("!d", x) + elif f == "o": + packed += struct.pack("!Bdd", tc.POSITION_2D, *v) + elif f == "O": + packed += struct.pack("!Bddd", tc.POSITION_3D, *v) + elif f == "g": + packed += struct.pack("!Bdd", tc.POSITION_LON_LAT, *v) + elif f == "G": + packed += struct.pack("!Bddd", tc.POSITION_LON_LAT_ALT, *v) + elif f == "r": + packed += struct.pack("!Bi", tc.POSITION_ROADMAP, len(v[0])) + v[0].encode("latin1") + packed += struct.pack("!dB", v[1], v[2]) + return packed + + def _sendCmd(self, cmdID, varID, objID, format="", *values): + self._queue.append(cmdID) + packed = self._pack(format, *values) + length = len(packed) + 1 + 1 # length and command + if varID is not None: + if isinstance(varID, tuple): # begin and end of a subscription + length += 8 + 8 + 4 + len(objID) + else: + length += 1 + 4 + len(objID) + if length <= 255: + self._string += struct.pack("!BB", length, cmdID) + else: + self._string += struct.pack("!BiB", 0, length + 4, cmdID) + if varID is not None: + if isinstance(varID, tuple): + self._string += struct.pack("!dd", *varID) + else: + self._string += struct.pack("!B", varID) + self._string += struct.pack("!i", len(objID)) + objID.encode("latin1") + self._string += packed + return self._sendExact() + + def _readSubscription(self, result): + # to enable this you also need to set _DEBUG to True in storage.py + # result.printDebug() + result.readLength() + response = result.read("!B")[0] + isVariableSubscription = ((response >= tc.RESPONSE_SUBSCRIBE_INDUCTIONLOOP_VARIABLE and + response <= tc.RESPONSE_SUBSCRIBE_BUSSTOP_VARIABLE) or + (response >= tc.RESPONSE_SUBSCRIBE_PARKINGAREA_VARIABLE and + response <= tc.RESPONSE_SUBSCRIBE_OVERHEADWIRE_VARIABLE)) + objectID = result.readString() + if not isVariableSubscription: + domain = result.read("!B")[0] + numVars = result.read("!B")[0] + if isVariableSubscription: + while numVars > 0: + varID, status = result.read("!BB") + if status: + print("Error!", result.readTypedString()) + elif response in self._subscriptionMapping: + self._subscriptionMapping[response].add(objectID, varID, result) + else: + raise FatalTraCIError( + "Cannot handle subscription response %02x for %s." % (response, objectID)) + numVars -= 1 + else: + objectNo = result.read("!i")[0] + for _ in range(objectNo): + oid = result.readString() + if numVars == 0: + self._subscriptionMapping[response].addContext( + objectID, self._subscriptionMapping[domain], oid) + for __ in range(numVars): + varID, status = result.read("!BB") + if status: + print("Error!", result.readTypedString()) + elif response in self._subscriptionMapping: + self._subscriptionMapping[response].addContext( + objectID, self._subscriptionMapping[domain], oid, varID, result) + else: + raise FatalTraCIError( + "Cannot handle subscription response %02x for %s." % (response, objectID)) + return objectID, response + + def _subscribe(self, cmdID, begin, end, objID, varIDs, parameters): + format = "u" + args = [len(varIDs)] + for v in varIDs: + format += "u" + args.append(v) + if parameters is not None and v in parameters: + if isinstance(parameters[v], tuple): + format += parameters[v][0] + for a in parameters[v][1:]: + args.append(a) + elif isinstance(parameters[v], int): + format += "i" + args.append(parameters[v]) + elif isinstance(parameters[v], float): + format += "d" + args.append(parameters[v]) + else: + format += "s" + args.append(parameters[v]) + result = self._sendCmd(cmdID, (begin, end), objID, format, *args) + if varIDs: + objectID, response = self._readSubscription(result) + if response - cmdID != 16 or objectID != objID: + raise FatalTraCIError("Received answer %02x,%s for subscription command %02x,%s." % ( + response, objectID, cmdID, objID)) + + def _getSubscriptionResults(self, cmdID): + return self._subscriptionMapping[cmdID] + + def _subscribeContext(self, cmdID, begin, end, objID, domain, dist, varIDs, parameters=None): + result = self._sendCmd(cmdID, (begin, end), objID, "uDu" + (len(varIDs) * "u"), + domain, dist, len(varIDs), *varIDs) + if varIDs: + objectID, response = self._readSubscription(result) + if response - cmdID != 16 or objectID != objID: + raise FatalTraCIError("Received answer %02x,%s for context subscription command %02x,%s." % ( + response, objectID, cmdID, objID)) + + def _addSubscriptionFilter(self, filterType, params=None): + if filterType in (tc.FILTER_TYPE_NONE, tc.FILTER_TYPE_NOOPPOSITE, + tc.FILTER_TYPE_LEAD_FOLLOW): + # filter without parameter + assert params is None + self._sendCmd(tc.CMD_ADD_SUBSCRIPTION_FILTER, None, None, "u", filterType) + elif filterType in (tc.FILTER_TYPE_DOWNSTREAM_DIST, tc.FILTER_TYPE_UPSTREAM_DIST, + tc.FILTER_TYPE_TURN, tc.FILTER_TYPE_FIELD_OF_VISION, + tc.FILTER_TYPE_LATERAL_DIST): + # filter with float parameter + self._sendCmd(tc.CMD_ADD_SUBSCRIPTION_FILTER, None, None, "ud", filterType, params) + elif filterType in (tc.FILTER_TYPE_VCLASS, tc.FILTER_TYPE_VTYPE): + # filter with list(string) parameter + self._sendCmd(tc.CMD_ADD_SUBSCRIPTION_FILTER, None, None, "ul", filterType, params) + elif filterType == tc.FILTER_TYPE_LANES: + # filter with list(byte) parameter + # check uniqueness of given lanes in list + lanes = set() + for i in params: + lane = int(i) + if lane < 0: + lane += 256 + lanes.add(lane) + if len(lanes) < len(list(params)): + warnings.warn("Ignoring duplicate lane specification for subscription filter.") + self._sendCmd(tc.CMD_ADD_SUBSCRIPTION_FILTER, None, None, + (len(lanes) + 2) * "u", filterType, len(lanes), *lanes) + + def hasGUI(self): + try: + self.gui.getIDList() + return True + except TraCIException: + return False + + def load(self, args): + """ + Load a simulation from the given arguments. + """ + if self._traceFile: + self._traceFile.write("traci.load(%s)\n" % repr(args)) + self._sendCmd(tc.CMD_LOAD, None, None, "l", args) + + def simulationStep(self, step=0.): + """ + Make a simulation step and simulate up to the given second in sim time. + If the given value is 0 or absent, exactly one step is performed. + Values smaller than or equal to the current sim time result in no action. + """ + if self._traceFile: + args = "" if step == 0 else str(step) + self._traceFile.write("traci.simulationStep(%s)\n" % args) + if type(step) is int and step >= 1000: + warnings.warn("API change now handles step as floating point seconds", stacklevel=2) + result = self._sendCmd(tc.CMD_SIMSTEP, None, None, "D", step) + for subscriptionResults in self._subscriptionMapping.values(): + subscriptionResults.reset() + numSubs = result.readInt() + responses = [] + while numSubs > 0: + responses.append(self._readSubscription(result)) + numSubs -= 1 + self._manageStepListeners(step) + return responses + + def _manageStepListeners(self, step): + listenersToRemove = [] + for (listenerID, listener) in self._stepListeners.items(): + keep = listener.step(step) + if not keep: + listenersToRemove.append(listenerID) + for listenerID in listenersToRemove: + self.removeStepListener(listenerID) + + def addStepListener(self, listener): + """addStepListener(traci.StepListener) -> int + + Append the step listener (its step function is called at the end of every call to traci.simulationStep()) + Returns the ID assigned to the listener if it was added successfully, None otherwise. + """ + if issubclass(type(listener), StepListener): + listener.setID(self._nextStepListenerID) + self._stepListeners[self._nextStepListenerID] = listener + self._nextStepListenerID += 1 + # print ("traci: Added stepListener %s\nlisteners: %s"%(_nextStepListenerID - 1, _stepListeners)) + return self._nextStepListenerID - 1 + warnings.warn( + "Proposed listener's type must inherit from traci.StepListener. Not adding object of type '%s'" % + type(listener)) + return None + + def removeStepListener(self, listenerID): + """removeStepListener(traci.StepListener) -> bool + + Remove the step listener from traci's step listener container. + Returns True if the listener was removed successfully, False if it wasn't registered. + """ + # print ("traci: removeStepListener %s\nlisteners: %s"%(listenerID, _stepListeners)) + if listenerID in self._stepListeners: + self._stepListeners[listenerID].cleanUp() + del self._stepListeners[listenerID] + # print ("traci: Removed stepListener %s"%(listenerID)) + return True + warnings.warn("Cannot remove unknown listener %s.\nlisteners:%s" % (listenerID, self._stepListeners)) + return False + + def getVersion(self): + command = tc.CMD_GETVERSION + result = self._sendCmd(command, None, None) + result.readLength() + response = result.read("!B")[0] + if response != command: + raise FatalTraCIError("Received answer %s for command %s." % (response, command)) + return result.readInt(), result.readString() + + def setOrder(self, order): + self._sendCmd(tc.CMD_SETORDER, None, None, "I", order) + + def close(self, wait=True): + if self._traceFile: + self._traceFile.write("traci.close()\n") + self._traceFile.close() + for domain in _defaultDomains: + domain._setTraceFile(None, False) + for listenerID in list(self._stepListeners.keys()): + self.removeStepListener(listenerID) + if self._socket is not None: + self._sendCmd(tc.CMD_CLOSE, None, None) + self._socket.close() + self._socket = None + if wait and self._process is not None: + self._process.wait() + + def getV2xMessage(self): + command = tc.CMD_GET_V2X + result = self._sendCmd(command,None,None) + result.readLength() + response = result.read("!B")[0] + + if response != command: + raise FatalTraCIError("Received answer %s for command %s." % (response, command)) + return result.readStringList() + + def setV2xMessage(self, message): + self._sendCmd(tc.CMD_SET_V2X, None, None, "s", message) + +class StepListener(object): + __metaclass__ = abc.ABCMeta + + @abc.abstractmethod + def step(self, t=0): + """step(int) -> bool + + After adding a StepListener 'listener' with traci.addStepListener(listener), + TraCI will call listener.step(t) after each call to traci.simulationStep(t) + The return value indicates whether the stepListener wants to stay active. + """ + return True + + def cleanUp(self): + """cleanUp() -> None + + This method is called at removal of the stepListener, allowing to schedule some final actions + """ + pass + + def setID(self, ID): + self._ID = ID + + def getID(self): + return self._ID diff --git a/co-simulation/traci_update/constants.py b/co-simulation/traci_update/constants.py new file mode 100644 index 00000000..3a2506df --- /dev/null +++ b/co-simulation/traci_update/constants.py @@ -0,0 +1,1399 @@ +# Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo +# Copyright (C) 2009-2022 German Aerospace Center (DLR) and others. +# This program and the accompanying materials are made available under the +# terms of the Eclipse Public License 2.0 which is available at +# https://www.eclipse.org/legal/epl-2.0/ +# This Source Code may also be made available under the following Secondary +# Licenses when the conditions for such availability set forth in the Eclipse +# Public License 2.0 are satisfied: GNU General Public License, version 2 +# or later which is available at +# https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html +# SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later + +# @file constants.py +# @author generated by "rebuildConstants.py" +# @date 2021-11-09 23:34:42.684719 + +""" +This script contains TraCI constant definitions from /src/libsumo/TraCIConstants.h. +""" + + +# **************************************** +# VERSION +# **************************************** +TRACI_VERSION = 20 + +# **************************************** +# COMMANDS +# **************************************** +# command: get version +CMD_GETVERSION = 0x00 + +# command: load +CMD_LOAD = 0x01 + +# command: simulation step +CMD_SIMSTEP = 0x02 + +# command: set connection priority (execution order) +CMD_SETORDER = 0x03 + +# command: stop vehicle +CMD_STOP = 0x12 + +# command: reroute to parking area +CMD_REROUTE_TO_PARKING = 0xc2 + +# command: Resume from parking +CMD_RESUME = 0x19 + +# command: set lane +CMD_CHANGELANE = 0x13 + +# command: slow down +CMD_SLOWDOWN = 0x14 + +# command: set sublane (vehicle) +CMD_CHANGESUBLANE = 0x15 + +# command: open gap +CMD_OPENGAP = 0x16 + +# command: replace vehicle stop and updated route +CMD_REPLACE_STOP = 0x17 + +# command: retrieve information about the current taxi fleet and their status +VAR_TAXI_FLEET = 0x20 + +# command: send dispatch request for the given taxi +CMD_TAXI_DISPATCH = 0x21 + +# command: change target +CMD_CHANGETARGET = 0x31 + +# command: close sumo +CMD_CLOSE = 0x7F + +# command: add subscription filter +CMD_ADD_SUBSCRIPTION_FILTER = 0x7e + +# command: get V2X message +CMD_GET_V2X = 0x0d + +# command: set V2X message +CMD_SET_V2X = 0x2f + +# command: subscribe induction loop (e1) context +CMD_SUBSCRIBE_INDUCTIONLOOP_CONTEXT = 0x80 +# response: subscribe induction loop (e1) context +RESPONSE_SUBSCRIBE_INDUCTIONLOOP_CONTEXT = 0x90 +# command: get induction loop (e1) variable +CMD_GET_INDUCTIONLOOP_VARIABLE = 0xa0 +# response: get induction loop (e1) variable +RESPONSE_GET_INDUCTIONLOOP_VARIABLE = 0xb0 +# command: set induction loop (e1) variable, not used yet +CMD_SET_INDUCTIONLOOP_VARIABLE = 0xc0 +# command: subscribe induction loop (e1) variable +CMD_SUBSCRIBE_INDUCTIONLOOP_VARIABLE = 0xd0 +# response: subscribe induction loop (e1) variable +RESPONSE_SUBSCRIBE_INDUCTIONLOOP_VARIABLE = 0xe0 + +# command: subscribe multi-entry/multi-exit detector (e3) context +CMD_SUBSCRIBE_MULTIENTRYEXIT_CONTEXT = 0x81 +# response: subscribe multi-entry/multi-exit detector (e3) context +RESPONSE_SUBSCRIBE_MULTIENTRYEXIT_CONTEXT = 0x91 +# command: get multi-entry/multi-exit detector (e3) variable +CMD_GET_MULTIENTRYEXIT_VARIABLE = 0xa1 +# response: get multi-entry/multi-exit detector (e3) variable +RESPONSE_GET_MULTIENTRYEXIT_VARIABLE = 0xb1 +# command: set multi-entry/multi-exit detector (e3) variable, not used yet +CMD_SET_MULTIENTRYEXIT_VARIABLE = 0xc1 +# command: subscribe multi-entry/multi-exit detector (e3) variable +CMD_SUBSCRIBE_MULTIENTRYEXIT_VARIABLE = 0xd1 +# response: subscribe multi-entry/multi-exit detector (e3) variable +RESPONSE_SUBSCRIBE_MULTIENTRYEXIT_VARIABLE = 0xe1 + +# command: subscribe traffic lights context +CMD_SUBSCRIBE_TL_CONTEXT = 0x82 +# response: subscribe traffic lights context +RESPONSE_SUBSCRIBE_TL_CONTEXT = 0x92 +# command: get traffic lights variable +CMD_GET_TL_VARIABLE = 0xa2 +# response: get traffic lights variable +RESPONSE_GET_TL_VARIABLE = 0xb2 +# command: set traffic lights variable +CMD_SET_TL_VARIABLE = 0xc2 +# command: subscribe traffic lights variable +CMD_SUBSCRIBE_TL_VARIABLE = 0xd2 +# response: subscribe traffic lights variable +RESPONSE_SUBSCRIBE_TL_VARIABLE = 0xe2 + +# command: subscribe lane context +CMD_SUBSCRIBE_LANE_CONTEXT = 0x83 +# response: subscribe lane context +RESPONSE_SUBSCRIBE_LANE_CONTEXT = 0x93 +# command: get lane variable +CMD_GET_LANE_VARIABLE = 0xa3 +# response: get lane variable +RESPONSE_GET_LANE_VARIABLE = 0xb3 +# command: set lane variable +CMD_SET_LANE_VARIABLE = 0xc3 +# command: subscribe lane variable +CMD_SUBSCRIBE_LANE_VARIABLE = 0xd3 +# response: subscribe lane variable +RESPONSE_SUBSCRIBE_LANE_VARIABLE = 0xe3 + +# command: subscribe vehicle context +CMD_SUBSCRIBE_VEHICLE_CONTEXT = 0x84 +# response: subscribe vehicle context +RESPONSE_SUBSCRIBE_VEHICLE_CONTEXT = 0x94 +# command: get vehicle variable +CMD_GET_VEHICLE_VARIABLE = 0xa4 +# response: get vehicle variable +RESPONSE_GET_VEHICLE_VARIABLE = 0xb4 +# command: set vehicle variable +CMD_SET_VEHICLE_VARIABLE = 0xc4 +# command: subscribe vehicle variable +CMD_SUBSCRIBE_VEHICLE_VARIABLE = 0xd4 +# response: subscribe vehicle variable +RESPONSE_SUBSCRIBE_VEHICLE_VARIABLE = 0xe4 + +# command: subscribe vehicle type context +CMD_SUBSCRIBE_VEHICLETYPE_CONTEXT = 0x85 +# response: subscribe vehicle type context +RESPONSE_SUBSCRIBE_VEHICLETYPE_CONTEXT = 0x95 +# command: get vehicle type variable +CMD_GET_VEHICLETYPE_VARIABLE = 0xa5 +# response: get vehicle type variable +RESPONSE_GET_VEHICLETYPE_VARIABLE = 0xb5 +# command: set vehicle type variable +CMD_SET_VEHICLETYPE_VARIABLE = 0xc5 +# command: subscribe vehicle type variable +CMD_SUBSCRIBE_VEHICLETYPE_VARIABLE = 0xd5 +# response: subscribe vehicle type variable +RESPONSE_SUBSCRIBE_VEHICLETYPE_VARIABLE = 0xe5 + +# command: subscribe route context +CMD_SUBSCRIBE_ROUTE_CONTEXT = 0x86 +# response: subscribe route context +RESPONSE_SUBSCRIBE_ROUTE_CONTEXT = 0x96 +# command: get route variable +CMD_GET_ROUTE_VARIABLE = 0xa6 +# response: get route variable +RESPONSE_GET_ROUTE_VARIABLE = 0xb6 +# command: set route variable +CMD_SET_ROUTE_VARIABLE = 0xc6 +# command: subscribe route variable +CMD_SUBSCRIBE_ROUTE_VARIABLE = 0xd6 +# response: subscribe route variable +RESPONSE_SUBSCRIBE_ROUTE_VARIABLE = 0xe6 + +# command: subscribe poi context +CMD_SUBSCRIBE_POI_CONTEXT = 0x87 +# response: subscribe poi context +RESPONSE_SUBSCRIBE_POI_CONTEXT = 0x97 +# command: get poi variable +CMD_GET_POI_VARIABLE = 0xa7 +# response: get poi variable +RESPONSE_GET_POI_VARIABLE = 0xb7 +# command: set poi variable +CMD_SET_POI_VARIABLE = 0xc7 +# command: subscribe poi variable +CMD_SUBSCRIBE_POI_VARIABLE = 0xd7 +# response: subscribe poi variable +RESPONSE_SUBSCRIBE_POI_VARIABLE = 0xe7 + +# command: subscribe polygon context +CMD_SUBSCRIBE_POLYGON_CONTEXT = 0x88 +# response: subscribe polygon context +RESPONSE_SUBSCRIBE_POLYGON_CONTEXT = 0x98 +# command: get polygon variable +CMD_GET_POLYGON_VARIABLE = 0xa8 +# response: get polygon variable +RESPONSE_GET_POLYGON_VARIABLE = 0xb8 +# command: set polygon variable +CMD_SET_POLYGON_VARIABLE = 0xc8 +# command: subscribe polygon variable +CMD_SUBSCRIBE_POLYGON_VARIABLE = 0xd8 +# response: subscribe polygon variable +RESPONSE_SUBSCRIBE_POLYGON_VARIABLE = 0xe8 + +# command: subscribe junction context +CMD_SUBSCRIBE_JUNCTION_CONTEXT = 0x89 +# response: subscribe junction context +RESPONSE_SUBSCRIBE_JUNCTION_CONTEXT = 0x99 +# command: get junction variable +CMD_GET_JUNCTION_VARIABLE = 0xa9 +# response: get junction variable +RESPONSE_GET_JUNCTION_VARIABLE = 0xb9 +# command: set junction variable +CMD_SET_JUNCTION_VARIABLE = 0xc9 +# command: subscribe junction variable +CMD_SUBSCRIBE_JUNCTION_VARIABLE = 0xd9 +# response: subscribe junction variable +RESPONSE_SUBSCRIBE_JUNCTION_VARIABLE = 0xe9 + +# command: subscribe edge context +CMD_SUBSCRIBE_EDGE_CONTEXT = 0x8a +# response: subscribe edge context +RESPONSE_SUBSCRIBE_EDGE_CONTEXT = 0x9a +# command: get edge variable +CMD_GET_EDGE_VARIABLE = 0xaa +# response: get edge variable +RESPONSE_GET_EDGE_VARIABLE = 0xba +# command: set edge variable +CMD_SET_EDGE_VARIABLE = 0xca +# command: subscribe edge variable +CMD_SUBSCRIBE_EDGE_VARIABLE = 0xda +# response: subscribe edge variable +RESPONSE_SUBSCRIBE_EDGE_VARIABLE = 0xea + +# command: subscribe simulation context +CMD_SUBSCRIBE_SIM_CONTEXT = 0x8b +# response: subscribe simulation context +RESPONSE_SUBSCRIBE_SIM_CONTEXT = 0x9b +# command: get simulation variable +CMD_GET_SIM_VARIABLE = 0xab +# response: get simulation variable +RESPONSE_GET_SIM_VARIABLE = 0xbb +# command: set simulation variable +CMD_SET_SIM_VARIABLE = 0xcb +# command: subscribe simulation variable +CMD_SUBSCRIBE_SIM_VARIABLE = 0xdb +# response: subscribe simulation variable +RESPONSE_SUBSCRIBE_SIM_VARIABLE = 0xeb + +# command: subscribe GUI context +CMD_SUBSCRIBE_GUI_CONTEXT = 0x8c +# response: subscribe GUI context +RESPONSE_SUBSCRIBE_GUI_CONTEXT = 0x9c +# command: get GUI variable +CMD_GET_GUI_VARIABLE = 0xac +# response: get GUI variable +RESPONSE_GET_GUI_VARIABLE = 0xbc +# command: set GUI variable +CMD_SET_GUI_VARIABLE = 0xcc +# command: subscribe GUI variable +CMD_SUBSCRIBE_GUI_VARIABLE = 0xdc +# response: subscribe GUI variable +RESPONSE_SUBSCRIBE_GUI_VARIABLE = 0xec + +# command: subscribe lane area detector (e2) context +CMD_SUBSCRIBE_LANEAREA_CONTEXT = 0x8d +# response: subscribe lane area detector (e2) context +RESPONSE_SUBSCRIBE_LANEAREA_CONTEXT = 0x9d +# command: get lane area detector (e2) variable +CMD_GET_LANEAREA_VARIABLE = 0xad +# response: get lane area detector (e2) variable +RESPONSE_GET_LANEAREA_VARIABLE = 0xbd +# command: set lane area detector (e2) variable, not used yet +CMD_SET_LANEAREA_VARIABLE = 0xcd +# command: subscribe lane area detector (e2) variable +CMD_SUBSCRIBE_LANEAREA_VARIABLE = 0xdd +# response: subscribe lane area detector (e2) variable +RESPONSE_SUBSCRIBE_LANEAREA_VARIABLE = 0xed + +# command: subscribe person context +CMD_SUBSCRIBE_PERSON_CONTEXT = 0x8e +# response: subscribe person context +RESPONSE_SUBSCRIBE_PERSON_CONTEXT = 0x9e +# command: get person variable +CMD_GET_PERSON_VARIABLE = 0xae +# response: get person variable +RESPONSE_GET_PERSON_VARIABLE = 0xbe +# command: set person variable +CMD_SET_PERSON_VARIABLE = 0xce +# command: subscribe person variable +CMD_SUBSCRIBE_PERSON_VARIABLE = 0xde +# response: subscribe person variable +RESPONSE_SUBSCRIBE_PERSON_VARIABLE = 0xee + +# command: subscribe busstop context +CMD_SUBSCRIBE_BUSSTOP_CONTEXT = 0x8f +# response: subscribe busstop context +RESPONSE_SUBSCRIBE_BUSSTOP_CONTEXT = 0x9f +# command: get busstop variable +CMD_GET_BUSSTOP_VARIABLE = 0xaf +# response: get busstop variable +RESPONSE_GET_BUSSTOP_VARIABLE = 0xbf +# command: set busstop variable, not used yet +CMD_SET_BUSSTOP_VARIABLE = 0xcf +# command: subscribe busstop variable +CMD_SUBSCRIBE_BUSSTOP_VARIABLE = 0xdf +# response: subscribe busstop variable +RESPONSE_SUBSCRIBE_BUSSTOP_VARIABLE = 0xef + +# command: subscribe parkingarea context +CMD_SUBSCRIBE_PARKINGAREA_CONTEXT = 0x04 +# response: subscribe parkingarea context +RESPONSE_SUBSCRIBE_PARKINGAREA_CONTEXT = 0x14 +# command: get parkingarea variable +CMD_GET_PARKINGAREA_VARIABLE = 0x24 +# response: get parkingarea variable +RESPONSE_GET_PARKINGAREA_VARIABLE = 0x34 +# command: set parkingarea variable +CMD_SET_PARKINGAREA_VARIABLE = 0x44 +# command: subscribe parkingarea variable +CMD_SUBSCRIBE_PARKINGAREA_VARIABLE = 0x54 +# response: subscribe parkingarea variable +RESPONSE_SUBSCRIBE_PARKINGAREA_VARIABLE = 0x64 + +# command: subscribe chargingstation context +CMD_SUBSCRIBE_CHARGINGSTATION_CONTEXT = 0x05 +# response: subscribe chargingstation context +RESPONSE_SUBSCRIBE_CHARGINGSTATION_CONTEXT = 0x15 +# command: get chargingstation variable +CMD_GET_CHARGINGSTATION_VARIABLE = 0x25 +# response: get chargingstation variable +RESPONSE_GET_CHARGINGSTATION_VARIABLE = 0x35 +# command: set chargingstation variable +CMD_SET_CHARGINGSTATION_VARIABLE = 0x45 +# command: subscribe chargingstation variable +CMD_SUBSCRIBE_CHARGINGSTATION_VARIABLE = 0x55 +# response: subscribe chargingstation variable +RESPONSE_SUBSCRIBE_CHARGINGSTATION_VARIABLE = 0x65 + +# command: subscribe routeprobe context +CMD_SUBSCRIBE_ROUTEPROBE_CONTEXT = 0x06 +# response: subscribe routeprobe context +RESPONSE_SUBSCRIBE_ROUTEPROBE_CONTEXT = 0x16 +# command: get routeprobe variable +CMD_GET_ROUTEPROBE_VARIABLE = 0x26 +# response: get routeprobe variable +RESPONSE_GET_ROUTEPROBE_VARIABLE = 0x36 +# command: set routeprobe variable +CMD_SET_ROUTEPROBE_VARIABLE = 0x46 +# command: subscribe routeprobe variable +CMD_SUBSCRIBE_ROUTEPROBE_VARIABLE = 0x56 +# response: subscribe routeprobe variable +RESPONSE_SUBSCRIBE_ROUTEPROBE_VARIABLE = 0x66 + +# command: subscribe calibrator context +CMD_SUBSCRIBE_CALIBRATOR_CONTEXT = 0x07 +# response: subscribe calibrator context +RESPONSE_SUBSCRIBE_CALIBRATOR_CONTEXT = 0x17 +# command: get calibrator variable +CMD_GET_CALIBRATOR_VARIABLE = 0x27 +# response: get calibrator variable +RESPONSE_GET_CALIBRATOR_VARIABLE = 0x37 +# command: set calibrator variable +CMD_SET_CALIBRATOR_VARIABLE = 0x47 +# command: subscribe calibrator variable +CMD_SUBSCRIBE_CALIBRATOR_VARIABLE = 0x57 +# response: subscribe calibrator variable +RESPONSE_SUBSCRIBE_CALIBRATOR_VARIABLE = 0x67 + +# command: subscribe rerouter context +CMD_SUBSCRIBE_REROUTER_CONTEXT = 0x08 +# response: subscribe rerouter context +RESPONSE_SUBSCRIBE_REROUTER_CONTEXT = 0x18 +# command: get rerouter variable +CMD_GET_REROUTER_VARIABLE = 0x28 +# response: get rerouter variable +RESPONSE_GET_REROUTER_VARIABLE = 0x38 +# command: set rerouter variable +CMD_SET_REROUTER_VARIABLE = 0x48 +# command: subscribe rerouter variable +CMD_SUBSCRIBE_REROUTER_VARIABLE = 0x58 +# response: subscribe rerouter variable +RESPONSE_SUBSCRIBE_REROUTER_VARIABLE = 0x68 + +# command: subscribe variablespeedsign context +CMD_SUBSCRIBE_VARIABLESPEEDSIGN_CONTEXT = 0x09 +# response: subscribe variablespeedsign context +RESPONSE_SUBSCRIBE_VARIABLESPEEDSIGN_CONTEXT = 0x19 +# command: get variablespeedsign variable +CMD_GET_VARIABLESPEEDSIGN_VARIABLE = 0x29 +# response: get variablespeedsign variable +RESPONSE_GET_VARIABLESPEEDSIGN_VARIABLE = 0x39 +# command: set variablespeedsign variable +CMD_SET_VARIABLESPEEDSIGN_VARIABLE = 0x49 +# command: subscribe variablespeedsign variable +CMD_SUBSCRIBE_VARIABLESPEEDSIGN_VARIABLE = 0x59 +# response: subscribe variablespeedsign variable +RESPONSE_SUBSCRIBE_VARIABLESPEEDSIGN_VARIABLE = 0x69 + +# command: subscribe meandata context +CMD_SUBSCRIBE_MEANDATA_CONTEXT = 0x0a +# response: subscribe meandata context +RESPONSE_SUBSCRIBE_MEANDATA_CONTEXT = 0x1a +# command: get meandata variable +CMD_GET_MEANDATA_VARIABLE = 0x2a +# response: get meandata variable +RESPONSE_GET_MEANDATA_VARIABLE = 0x3a +# command: set meandata variable, not used yet +CMD_SET_MEANDATA_VARIABLE = 0x4a +# command: subscribe meandata variable +CMD_SUBSCRIBE_MEANDATA_VARIABLE = 0x5a +# response: subscribe meandata variable +RESPONSE_SUBSCRIBE_MEANDATA_VARIABLE = 0x6a + +# command: subscribe overheadwire context +CMD_SUBSCRIBE_OVERHEADWIRE_CONTEXT = 0x0b +# response: subscribe overheadwire context +RESPONSE_SUBSCRIBE_OVERHEADWIRE_CONTEXT = 0x1b +# command: get overheadwire variable +CMD_GET_OVERHEADWIRE_VARIABLE = 0x2b +# response: get overheadwire variable +RESPONSE_GET_OVERHEADWIRE_VARIABLE = 0x3b +# command: set overheadwire variable +CMD_SET_OVERHEADWIRE_VARIABLE = 0x4b +# command: subscribe overheadwire variable +CMD_SUBSCRIBE_OVERHEADWIRE_VARIABLE = 0x5b +# response: subscribe overheadwire variable +RESPONSE_SUBSCRIBE_OVERHEADWIRE_VARIABLE = 0x6b + + +# **************************************** +# POSITION REPRESENTATIONS +# **************************************** +# Position in geo-coordinates +POSITION_LON_LAT = 0x00 +# 2D cartesian coordinates +POSITION_2D = 0x01 +# Position in geo-coordinates with altitude +POSITION_LON_LAT_ALT = 0x02 +# 3D cartesian coordinates +POSITION_3D = 0x03 +# Position on road map +POSITION_ROADMAP = 0x04 + + +# **************************************** +# DATA TYPES +# **************************************** +# Polygon (2*n doubles) +TYPE_POLYGON = 0x06 +# unsigned byte +TYPE_UBYTE = 0x07 +# signed byte +TYPE_BYTE = 0x08 +# 32 bit signed integer +TYPE_INTEGER = 0x09 +# double precision float +TYPE_DOUBLE = 0x0B +# 8 bit ASCII string +TYPE_STRING = 0x0C +# list of strings +TYPE_STRINGLIST = 0x0E +# compound object +TYPE_COMPOUND = 0x0F +# list of double precision floats +TYPE_DOUBLELIST = 0x10 +# color (four ubytes) +TYPE_COLOR = 0x11 + + +# **************************************** +# RESULT TYPES +# **************************************** +# result type: Ok +RTYPE_OK = 0x00 +# result type: not implemented +RTYPE_NOTIMPLEMENTED = 0x01 +# result type: error +RTYPE_ERR = 0xFF + +# **************************************** +# special return or parameter values +# **************************************** +# return value for invalid queries (especially vehicle is not on the road), see Position::INVALID +INVALID_DOUBLE_VALUE = -1073741824.0 +# return value for invalid queries (especially vehicle is not on the road), see Position::INVALID +INVALID_INT_VALUE = -1073741824 +# maximum value for client ordering (2 ^ 30) +MAX_ORDER = 1073741824 +# default number of connection attempts +DEFAULT_NUM_RETRIES = 60 + + +# **************************************** +# DIFFERENT DISTANCE REQUESTS +# **************************************** +# air distance +REQUEST_AIRDIST = 0x00 +# driving distance +REQUEST_DRIVINGDIST = 0x01 + + +# **************************************** +# VEHICLE REMOVAL REASONS +# **************************************** +# vehicle started teleport +REMOVE_TELEPORT = 0x00 +# vehicle removed while parking +REMOVE_PARKING = 0x01 +# vehicle arrived +REMOVE_ARRIVED = 0x02 +# vehicle was vaporized +REMOVE_VAPORIZED = 0x03 +# vehicle finished route during teleport +REMOVE_TELEPORT_ARRIVED = 0x04 + +# **************************************** +# VEHICLE MOVE REASONS +# **************************************** +# infer reason from move distance +MOVE_AUTOMATIC = 0x00 +# vehicle teleports to another location +MOVE_TELEPORT = 0x01 +# vehicle moved normally +MOVE_NORMAL = 0x02 + +# **************************************** +# PERSON/CONTAINER STAGES +# **************************************** +# person / container stopping +STAGE_WAITING_FOR_DEPART = 0x00 +# person / container stopping +STAGE_WAITING = 0x01 +# person walking +STAGE_WALKING = 0x02 +# person riding / container being transported +STAGE_DRIVING = 0x03 +# person accessing stopping place +STAGE_ACCESS = 0x04 +# stage for encoding abstract travel demand +STAGE_TRIP = 0x05 +# person / container transhiping +STAGE_TRANSHIP = 0x06 + +# **************************************** +# Stop Flags +# **************************************** +STOP_DEFAULT = 0x00 +STOP_PARKING = 0x01 +STOP_TRIGGERED = 0x02 +STOP_CONTAINER_TRIGGERED = 0x04 +STOP_BUS_STOP = 0x08 +STOP_CONTAINER_STOP = 0x10 +STOP_CHARGING_STATION = 0x20 +STOP_PARKING_AREA = 0x40 +STOP_OVERHEAD_WIRE = 0x80 + +# **************************************** +# Departure Flags +# **************************************** +DEPARTFLAG_TRIGGERED = -0x01 +DEPARTFLAG_CONTAINER_TRIGGERED = -0x02 +DEPARTFLAG_NOW = -0x03 + +DEPARTFLAG_SPEED_RANDOM = -0x02 +DEPARTFLAG_SPEED_MAX = -0x03 + +DEPARTFLAG_LANE_RANDOM = -0x02 +DEPARTFLAG_LANE_FREE = -0x03 +DEPARTFLAG_LANE_ALLOWED_FREE = -0x04 +DEPARTFLAG_LANE_BEST_FREE = -0x05 +DEPARTFLAG_LANE_FIRST_ALLOWED = -0x06 + +DEPARTFLAG_POS_RANDOM = -0x02 +DEPARTFLAG_POS_FREE = -0x03 +DEPARTFLAG_POS_BASE = -0x04 +DEPARTFLAG_POS_LAST = -0x05 +DEPARTFLAG_POS_RANDOM_FREE = -0x06 + +ARRIVALFLAG_LANE_CURRENT = -0x02 +ARRIVALFLAG_SPEED_CURRENT = -0x02 + +ARRIVALFLAG_POS_RANDOM = -0x02 +ARRIVALFLAG_POS_MAX = -0x03 + +# **************************************** +# Routing modes +# **************************************** +# use custom weights if available, fall back to loaded weights and then to free-flow speed +ROUTING_MODE_DEFAULT = 0x00 +# use aggregated travel times from device.rerouting +ROUTING_MODE_AGGREGATED = 0x01 +# use loaded efforts +ROUTING_MODE_EFFORT = 0x02 +# use combined costs +ROUTING_MODE_COMBINED = 0x03 + +# **************************************** +# Traffic light types +# **************************************** +TRAFFICLIGHT_TYPE_STATIC = 0x00 +TRAFFICLIGHT_TYPE_ACTUATED = 0x03 +TRAFFICLIGHT_TYPE_DELAYBASED = 0x04 + +# **************************************** +# FILTER TYPES (for context subscription filters) +# **************************************** + +# Reset all filters +FILTER_TYPE_NONE = 0x00 + +# Filter by list of lanes relative to ego vehicle +FILTER_TYPE_LANES = 0x01 + +# Exclude vehicles on opposite (and other) lanes from context subscription result +FILTER_TYPE_NOOPPOSITE = 0x02 + +# Specify maximal downstream distance for vehicles in context subscription result +FILTER_TYPE_DOWNSTREAM_DIST = 0x03 + +# Specify maximal upstream distance for vehicles in context subscription result +FILTER_TYPE_UPSTREAM_DIST = 0x04 + +# Only return leader and follower on the specified lanes in context subscription result +FILTER_TYPE_LEAD_FOLLOW = 0x05 + +# Only return foes on upcoming junctions in context subscription result +FILTER_TYPE_TURN = 0x07 + +# Only return vehicles of the given vClass in context subscription result +FILTER_TYPE_VCLASS = 0x08 + +# Only return vehicles of the given vType in context subscription result +FILTER_TYPE_VTYPE = 0x09 + +# Only return vehicles within field of vision in context subscription result +FILTER_TYPE_FIELD_OF_VISION = 0x0A + +# Only return vehicles within the given lateral distance in context subscription result +FILTER_TYPE_LATERAL_DIST = 0x0B + +# **************************************** +# VARIABLE TYPES (for CMD_GET_*_VARIABLE) +# **************************************** +# list of instances' ids (get: all) +TRACI_ID_LIST = 0x00 + +# count of instances (get: all) +ID_COUNT = 0x01 + +# subscribe object variables (get: all) +AUTOMATIC_VARIABLES_SUBSCRIPTION = 0x02 + +# subscribe context variables (get: all) +AUTOMATIC_CONTEXT_SUBSCRIPTION = 0x03 + +# generic attributes (get/set: all) +GENERIC_ATTRIBUTE = 0x03 + +# last step vehicle number (get: induction loops, multi-entry/multi-exit detector, lanes, edges) +LAST_STEP_VEHICLE_NUMBER = 0x10 + +# last step vehicle number (get: induction loops, multi-entry/multi-exit detector, lanes, edges) +LAST_STEP_MEAN_SPEED = 0x11 + +# last step vehicle list (get: induction loops, multi-entry/multi-exit detector, lanes, edges) +LAST_STEP_VEHICLE_ID_LIST = 0x12 + +# last step occupancy (get: induction loops, lanes, edges) +LAST_STEP_OCCUPANCY = 0x13 + +# last step vehicle halting number (get: multi-entry/multi-exit detector, lanes, edges) +LAST_STEP_VEHICLE_HALTING_NUMBER = 0x14 + +# last step mean vehicle length (get: induction loops, lanes, edges) +LAST_STEP_LENGTH = 0x15 + +# last step time since last detection (get: induction loops) +LAST_STEP_TIME_SINCE_DETECTION = 0x16 + +# entry times +LAST_STEP_VEHICLE_DATA = 0x17 + +# last step jam length in vehicles +JAM_LENGTH_VEHICLE = 0x18 + +# last step jam length in meters +JAM_LENGTH_METERS = 0x19 + +# last interval travel time (get: e3) +VAR_LAST_INTERVAL_TRAVELTIME = 0x58 + +# last step vehicle halting number (get: multi-entry/multi-exit detector) +VAR_LAST_INTERVAL_MEAN_HALTING_NUMBER = 0x20 + +# last interval vehicle count(get: e3) +VAR_LAST_INTERVAL_VEHICLE_NUMBER = 0x21 + +# last step person list (get: edges, vehicles) +LAST_STEP_PERSON_ID_LIST = 0x1a + +# full name (get: edges, simulation, trafficlight) +VAR_NAME = 0x1b + +# carFollowModel function followSpeed (get: vehicle) +VAR_FOLLOW_SPEED = 0x1c + +# carFollowModel function stopSpeed (get: vehicle) +VAR_STOP_SPEED = 0x1d + +# carFollowModel function getSecureGap (get: vehicle) +VAR_SECURE_GAP = 0x1e + +# estimated (depart) delay for next stop (get: vehicle) +VAR_STOP_DELAY = 0x1f + +# estimated arrival delay for next stop (get: vehicle) +VAR_STOP_ARRIVALDELAY = 0x22 + +# collected timeLoss since departure (get: vehicle, e3) +VAR_TIMELOSS = 0x8c + +# begin time(get: calibrator) +VAR_BEGIN = 0x1c + +# end time(get: calibrator, simulation) +VAR_END = 0x1d + +# vtype list (get: calibrator) +VAR_VTYPES = 0x1e + +# vehicles per hour (get: calibrator) +VAR_VEHSPERHOUR = 0x13 + +# passed vehicle count (get: calibrator) +VAR_PASSED = 0x14 + +# inserted vehicle count (get: calibrator) +VAR_INSERTED = 0x15 + +# removed vehicle count (get: calibrator) +VAR_REMOVED = 0x16 + +# routeProbe id (get: calibrator) +VAR_ROUTE_PROBE = 0x17 + +# routeProbe id (get: calibrator) +CMD_SET_FLOW = 0x18 + +# traffic light states, encoded as rRgGyYoO tuple (get: traffic lights) +TL_RED_YELLOW_GREEN_STATE = 0x20 + +# index of the phase (set: traffic lights) +TL_PHASE_INDEX = 0x22 + +# traffic light program (set: traffic lights) +TL_PROGRAM = 0x23 + +# phase duration (set: traffic lights) +TL_PHASE_DURATION = 0x24 + +# vehicles that block passing the given signal (get: traffic lights) +TL_BLOCKING_VEHICLES = 0x25 + +# controlled lanes (get: traffic lights) +TL_CONTROLLED_LANES = 0x26 + +# controlled links (get: traffic lights) +TL_CONTROLLED_LINKS = 0x27 + +# index of the current phase (get: traffic lights) +TL_CURRENT_PHASE = 0x28 + +# name of the current program (get: traffic lights) +TL_CURRENT_PROGRAM = 0x29 + +# vehicles that also wish to pass the given signal (get: traffic lights) +TL_RIVAL_VEHICLES = 0x30 + +# vehicles that also wish to pass the given signal and have higher priority (get: traffic lights) +TL_PRIORITY_VEHICLES = 0x31 + +# controlled junctions (get: traffic lights) +TL_CONTROLLED_JUNCTIONS = 0x2a + +# complete definition (get: traffic lights) +TL_COMPLETE_DEFINITION_RYG = 0x2b + +# complete program (set: traffic lights) +TL_COMPLETE_PROGRAM_RYG = 0x2c + +# assumed time to next switch (get: traffic lights) +TL_NEXT_SWITCH = 0x2d + +# current state, using external signal names (get: traffic lights) +TL_EXTERNAL_STATE = 0x2e + +# add/get rail signal constraints +TL_CONSTRAINT = 0x2f + +# switch order of trains encoded in rail signal constraints (set: traffic lights) +TL_CONSTRAINT_SWAP = 0x32 + +# add/get rail signal constraints by foeSignal (get: traffic lights) +TL_CONSTRAINT_BYFOE = 0x34 + +# add/get rail signal constraints by foeSignal (set: traffic lights) +TL_CONSTRAINT_REMOVE = 0x35 + +# outgoing link number (get: lanes) +LANE_LINK_NUMBER = 0x30 + +# id of parent edge (get: lanes) +LANE_EDGE_ID = 0x31 + +# outgoing link definitions (get: lanes) +LANE_LINKS = 0x33 + +# list of allowed vehicle classes (get&set: lanes) +LANE_ALLOWED = 0x34 + +# list of not allowed vehicle classes (get&set: lanes) +LANE_DISALLOWED = 0x35 + +# list of foe lanes (get: lanes) +VAR_FOES = 0x37 + +# slope (get: edge, lane, vehicle, person) +VAR_SLOPE = 0x36 + +# speed (get: vehicle) +VAR_SPEED = 0x40 + +# adapt previous speed (set: vehicle) +VAR_PREV_SPEED = 0x3c + +# lateral speed (get: vehicle) +VAR_SPEED_LAT = 0x32 + +# maximum allowed/possible speed (get: vehicle types, lanes, set: edges, lanes) +VAR_MAXSPEED = 0x41 + +# position (2D) (get: vehicle, poi, inductionloop, lane area detector; set: poi) +VAR_POSITION = 0x42 + +# position (3D) (get: vehicle, poi, set: poi) +VAR_POSITION3D = 0x39 + +# angle (get: vehicle, poi; set: poi) +VAR_ANGLE = 0x43 + +# length (get: vehicle types, lanes, lane area detector, set: lanes) +VAR_LENGTH = 0x44 + +# color (get: vehicles, vehicle types, polygons, pois) +VAR_COLOR = 0x45 + +# max. acceleration (get: vehicles, vehicle types) +VAR_ACCEL = 0x46 + +# max. comfortable deceleration (get: vehicles, vehicle types) +VAR_DECEL = 0x47 + +# max. (physically possible) deceleration (get: vehicles, vehicle types) +VAR_EMERGENCY_DECEL = 0x7b + +# apparent deceleration (get: vehicles, vehicle types) +VAR_APPARENT_DECEL = 0x7c + +# action step length (get: vehicles, vehicle types) +VAR_ACTIONSTEPLENGTH = 0x7d + +# last action time (get: vehicles) +VAR_LASTACTIONTIME = 0x7f + +# driver's desired headway (get: vehicle types) +VAR_TAU = 0x48 + +# vehicle class (get: vehicle types) +VAR_VEHICLECLASS = 0x49 + +# emission class (get: vehicle types) +VAR_EMISSIONCLASS = 0x4a + +# shape class (get: vehicle types) +VAR_SHAPECLASS = 0x4b + +# minimum gap (get: vehicle types) +VAR_MINGAP = 0x4c + +# width (get: vehicle types, lanes, polygons, poi) +VAR_WIDTH = 0x4d + +# shape (get: polygons) +VAR_SHAPE = 0x4e + +# type id (get: vehicles, polygons, pois) +VAR_TYPE = 0x4f + +# road id (get: vehicles) +VAR_ROAD_ID = 0x50 + +# lane id (get: vehicles, inductionloop, lane area detector) +VAR_LANE_ID = 0x51 + +# lane index (get: vehicle, edge) +VAR_LANE_INDEX = 0x52 + +# route id (get & set: vehicles) +VAR_ROUTE_ID = 0x53 + +# edges (get: routes, vehicles) +VAR_EDGES = 0x54 + +# lanes (get: variablespeedsign) +VAR_LANES = 0x30 + +# update bestLanes (set: vehicle) +VAR_UPDATE_BESTLANES = 0x6a + +# filled? (get: polygons) +VAR_FILL = 0x55 + +# get/set image file (poi, poly, vehicle, person, simulation) +VAR_IMAGEFILE = 0x93 + +# position (1D along lane) (get: vehicle) +VAR_LANEPOSITION = 0x56 + +# route (set: vehicles) +VAR_ROUTE = 0x57 + +# travel time information (get&set: vehicle) +VAR_EDGE_TRAVELTIME = 0x58 + +# effort information (get&set: vehicle) +VAR_EDGE_EFFORT = 0x59 + +# last step travel time (get: edge, lane, e3) +VAR_CURRENT_TRAVELTIME = 0x5a + +# signals state (get/set: vehicle) +VAR_SIGNALS = 0x5b + +# vehicle: new lane/position along (set: vehicle) +VAR_MOVE_TO = 0x5c + +# polygon: add dynamics (set: polygon) +VAR_ADD_DYNAMICS = 0x5c + +# vehicle: highlight (set: vehicle, poi) +VAR_HIGHLIGHT = 0x6c + +# driver imperfection (set: vehicle) +VAR_IMPERFECTION = 0x5d + +# speed factor (set: vehicle) +VAR_SPEED_FACTOR = 0x5e + +# speed deviation (set: vehicle) +VAR_SPEED_DEVIATION = 0x5f + +# routing mode (get/set: vehicle) +VAR_ROUTING_MODE = 0x89 + +# speed without TraCI influence (get: vehicle) +VAR_SPEED_WITHOUT_TRACI = 0xb1 + +# best lanes (get: vehicle) +VAR_BEST_LANES = 0xb2 + +# how speed is set (set: vehicle) +VAR_SPEEDSETMODE = 0xb3 + +# move vehicle to explicit (remote controlled) position (set: vehicle) +MOVE_TO_XY = 0xb4 + +# is the vehicle stopped, and if so parked and/or triggered? +# value = stopped + 2 * parking + 4 * triggered +VAR_STOPSTATE = 0xb5 + +# how lane changing is performed (get/set: vehicle) +VAR_LANECHANGE_MODE = 0xb6 + +# maximum speed regarding max speed on the current lane and speed factor (get: vehicle) +VAR_ALLOWED_SPEED = 0xb7 + +# position (1D lateral position relative to center of the current lane) (get: vehicle) +VAR_LANEPOSITION_LAT = 0xb8 + +# get/set prefered lateral alignment within the lane (vehicle) +VAR_LATALIGNMENT = 0xb9 + +# get/set maximum lateral speed (vehicle, vtypes) +VAR_MAXSPEED_LAT = 0xba + +# get/set minimum lateral gap (vehicle, vtypes) +VAR_MINGAP_LAT = 0xbb + +# get/set vehicle height (vehicle, vtypes, poi) +VAR_HEIGHT = 0xbc + +# get/set vehicle line +VAR_LINE = 0xbd + +# get/set vehicle via +VAR_VIA = 0xbe + +# get (lane change relevant) neighboring vehicles (vehicles) +VAR_NEIGHBORS = 0xbf + +# current CO2 emission of a node (get: vehicle, lane, edge) +VAR_CO2EMISSION = 0x60 + +# current CO emission of a node (get: vehicle, lane, edge) +VAR_COEMISSION = 0x61 + +# current HC emission of a node (get: vehicle, lane, edge) +VAR_HCEMISSION = 0x62 + +# current PMx emission of a node (get: vehicle, lane, edge) +VAR_PMXEMISSION = 0x63 + +# current NOx emission of a node (get: vehicle, lane, edge) +VAR_NOXEMISSION = 0x64 + +# current fuel consumption of a node (get: vehicle, lane, edge) +VAR_FUELCONSUMPTION = 0x65 + +# current noise emission of a node (get: vehicle, lane, edge) +VAR_NOISEEMISSION = 0x66 + +# current person number (get: vehicle, trafficlight) +VAR_PERSON_NUMBER = 0x67 + +# person capacity (vehicle , vehicle type) +VAR_PERSON_CAPACITY = 0x38 + +VAR_BUS_STOP_ID_LIST = 0x9f + +# number of persons waiting at a defined bus stop (get: simulation) +VAR_BUS_STOP_WAITING = 0x67 + +# ids of persons waiting at a defined bus stop (get: simulation) +VAR_BUS_STOP_WAITING_IDS = 0xef + +# current leader together with gap (get: vehicle) +VAR_LEADER = 0x68 + +# current leader together with gap (get: vehicle) +VAR_FOLLOWER = 0x78 + +# edge index in current route (get: vehicle) +VAR_ROUTE_INDEX = 0x69 + +# current waiting time (get: vehicle, lane) +VAR_WAITING_TIME = 0x7a + +# current waiting time (get: vehicle) +VAR_ACCUMULATED_WAITING_TIME = 0x87 + +# upcoming traffic lights (get: vehicle) +VAR_NEXT_TLS = 0x70 + +# upcoming stops (get: vehicle) +VAR_NEXT_STOPS = 0x73 + +# upcoming stops with selection (get: vehicle) +VAR_NEXT_STOPS2 = 0x74 + +# current acceleration (get: vehicle) +VAR_ACCELERATION = 0x72 + +# arrival position (get,set: vehicle) +VAR_ARRIVALPOS = 0x75 + +# arrival lane (get,set: vehicle) +VAR_ARRIVALLANE = 0x76 + +# arrival speed (get,set: vehicle) +VAR_ARRIVALSPEED = 0x77 + +# add log message (set: simulation) +CMD_MESSAGE = 0x65 + +# current time in seconds (get: simulation) +VAR_TIME = 0x66 + +# current time step (get: simulation) +VAR_TIME_STEP = 0x70 + +# current electricity consumption of a node (get: vehicle, lane, edge) +VAR_ELECTRICITYCONSUMPTION = 0x71 + +# number of loaded vehicles (get: simulation) +VAR_LOADED_VEHICLES_NUMBER = 0x71 + +# loaded vehicle ids (get: simulation) +VAR_LOADED_VEHICLES_IDS = 0x72 + +# number of departed vehicle (get: simulation) +VAR_DEPARTED_VEHICLES_NUMBER = 0x73 + +# departed vehicle ids (get: simulation) +VAR_DEPARTED_VEHICLES_IDS = 0x74 + +# number of vehicles starting to teleport (get: simulation) +VAR_TELEPORT_STARTING_VEHICLES_NUMBER = 0x75 + +# ids of vehicles starting to teleport (get: simulation) +VAR_TELEPORT_STARTING_VEHICLES_IDS = 0x76 + +# number of vehicles ending to teleport (get: simulation) +VAR_TELEPORT_ENDING_VEHICLES_NUMBER = 0x77 + +# ids of vehicles ending to teleport (get: simulation) +VAR_TELEPORT_ENDING_VEHICLES_IDS = 0x78 + +# number of arrived vehicles (get: simulation) +VAR_ARRIVED_VEHICLES_NUMBER = 0x79 + +# ids of arrived vehicles (get: simulation) +VAR_ARRIVED_VEHICLES_IDS = 0x7a + +# delta t (get: simulation) +VAR_DELTA_T = 0x7b + +# bounding box (get: simulation) +VAR_NET_BOUNDING_BOX = 0x7c + +# minimum number of expected vehicles (get: simulation) +VAR_MIN_EXPECTED_VEHICLES = 0x7d + +# number of departed persons (get: simulation) +VAR_DEPARTED_PERSONS_NUMBER = 0x24 + +# departed person ids (get: simulation) +VAR_DEPARTED_PERSONS_IDS = 0x25 + +# number of arrived persons (get: simulation) +VAR_ARRIVED_PERSONS_NUMBER = 0x26 + +# ids of arrived persons (get: simulation) +VAR_ARRIVED_PERSONS_IDS = 0x27 + +# number of vehicles starting to park (get: simulation) +VAR_STOP_STARTING_VEHICLES_NUMBER = 0x68 + +# ids of vehicles starting to park (get: simulation) +VAR_STOP_STARTING_VEHICLES_IDS = 0x69 + +# number of vehicles ending to park (get: simulation) +VAR_STOP_ENDING_VEHICLES_NUMBER = 0x6a + +# ids of vehicles ending to park (get: simulation) +VAR_STOP_ENDING_VEHICLES_IDS = 0x6b + +# number of vehicles starting to park (get: simulation) +VAR_PARKING_STARTING_VEHICLES_NUMBER = 0x6c + +# ids of vehicles starting to park (get: simulation) +VAR_PARKING_STARTING_VEHICLES_IDS = 0x6d + +# number of vehicles maneuvering (get: simulation) +VAR_PARKING_MANEUVERING_VEHICLES_NUMBER = 0x3a + +# ids of vehicles maneuvering (get: simulation) +VAR_PARKING_MANEUVERING_VEHICLES_IDS = 0x3b + +# number of vehicles ending to park (get: simulation) +VAR_PARKING_ENDING_VEHICLES_NUMBER = 0x6e + +# ids of vehicles ending to park (get: simulation) +VAR_PARKING_ENDING_VEHICLES_IDS = 0x6f + +# number of vehicles involved in a collision (get: simulation) +VAR_COLLIDING_VEHICLES_NUMBER = 0x80 + +# ids of vehicles involved in a collision (get: simulation) +VAR_COLLIDING_VEHICLES_IDS = 0x81 + +# number of vehicles involved in a collision (get: simulation) +VAR_EMERGENCYSTOPPING_VEHICLES_NUMBER = 0x89 + +# ids of vehicles involved in a collision (get: simulation) +VAR_EMERGENCYSTOPPING_VEHICLES_IDS = 0x8a + +# clears the simulation of all not inserted vehicles (set: simulation) +CMD_CLEAR_PENDING_VEHICLES = 0x94 + +# retrieve number of not inserted vehicles (get: simulation, edge, lane) +VAR_PENDING_VEHICLES = 0x94 + +# triggers saving simulation state (set: simulation) +CMD_SAVE_SIMSTATE = 0x95 + +# triggers saving simulation state (set: simulation) +CMD_LOAD_SIMSTATE = 0x96 + +# retrieve detail data for each collision +VAR_COLLISIONS = 0x23 + +# sets/retrieves abstract parameter +VAR_PARAMETER = 0x7e + +# retrieves abstract parameter and returns (key, value) tuple +VAR_PARAMETER_WITH_KEY = 0x3e + + +# add an instance (poi, polygon, vehicle, person, route) +ADD = 0x80 + +# remove an instance (poi, polygon, vehicle, person) +REMOVE = 0x81 + +# copy an instance (vehicle type, other TBD.) +COPY = 0x88 + +# convert coordinates +POSITION_CONVERSION = 0x82 + +# distance between points or vehicles +DISTANCE_REQUEST = 0x83 + +# the current driving distance +VAR_DISTANCE = 0x84 + +# add a fully specified instance (vehicle) +ADD_FULL = 0x85 + +# find a car based route +FIND_ROUTE = 0x86 + +# find an intermodal route +FIND_INTERMODAL_ROUTE = 0x87 + +# force rerouting based on travel time (vehicles) +CMD_REROUTE_TRAVELTIME = 0x90 + +# force rerouting based on effort (vehicles) +CMD_REROUTE_EFFORT = 0x91 + +# validates current route (vehicles) +VAR_ROUTE_VALID = 0x92 + +# retrieve information regarding the current person/container stage +VAR_STAGE = 0xc0 + +# retrieve information regarding the next edge including crossings and walkingAreas (pedestrians only) +VAR_NEXT_EDGE = 0xc1 + +# retrieve information regarding the number of remaining stages +VAR_STAGES_REMAINING = 0xc2 + +# retrieve the current vehicle id for the driving stage (person, container) +VAR_VEHICLE = 0xc3 + +# append a person stage (person) +APPEND_STAGE = 0xc4 + +# replace a person stage (person) +REPLACE_STAGE = 0xcd + +# append a person stage (person) +REMOVE_STAGE = 0xc5 + +# retrieve taxi reservation (person) +VAR_TAXI_RESERVATIONS = 0xc6 + +# manipulate taxi reservation (person) +SPLIT_TAXI_RESERVATIONS = 0xc7 + +# sample last route (routeprobe) +VAR_SAMPLE_LAST = 0x20 + +# sample current route (routeprobe) +VAR_SAMPLE_CURRENT = 0x21 + +# zoom +VAR_VIEW_ZOOM = 0xa0 + +# view position +VAR_VIEW_OFFSET = 0xa1 + +# view schema +VAR_VIEW_SCHEMA = 0xa2 + +# view by boundary +VAR_VIEW_BOUNDARY = 0xa3 + +# select/deselect object (gui) +VAR_SELECT = 0xa4 + +# screenshot +VAR_SCREENSHOT = 0xa5 + +# track vehicle +VAR_TRACK_VEHICLE = 0xa6 + +# presence of view +VAR_HAS_VIEW = 0xa7 + +# @name currently wanted lane-change action +# @{ +# @brief No action desired +LCA_NONE = 0 +# @brief Needs to stay on the current lane +LCA_STAY = 1 << 0 +# @brief Wants go to the left +LCA_LEFT = 1 << 1 +# @brief Wants go to the right +LCA_RIGHT = 1 << 2 +# @brief The action is needed to follow the route (navigational lc) +LCA_STRATEGIC = 1 << 3 +# @brief The action is done to help someone else +LCA_COOPERATIVE = 1 << 4 +# @brief The action is due to the wish to be faster (tactical lc) +LCA_SPEEDGAIN = 1 << 5 +# @brief The action is due to the default of keeping right "Rechtsfahrgebot" +LCA_KEEPRIGHT = 1 << 6 +# @brief The action is due to a TraCI request +LCA_TRACI = 1 << 7 +# @brief The action is urgent (to be defined by lc-model) +LCA_URGENT = 1 << 8 +# @brief The action has not been determined +LCA_UNKNOWN = 1 << 30 +# @} + +# @name External state +# @{ +# @brief The vehicle is blocked by left leader +LCA_BLOCKED_BY_LEFT_LEADER = 1 << 9 +# @brief The vehicle is blocked by left follower +LCA_BLOCKED_BY_LEFT_FOLLOWER = 1 << 10 +# @brief The vehicle is blocked by right leader +LCA_BLOCKED_BY_RIGHT_LEADER = 1 << 11 +# @brief The vehicle is blocked by right follower +LCA_BLOCKED_BY_RIGHT_FOLLOWER = 1 << 12 +# @brief The vehicle is blocked being overlapping +LCA_OVERLAPPING = 1 << 13 +# @brief The vehicle does not have enough space to complete a continuous change before the next turn +LCA_INSUFFICIENT_SPACE = 1 << 14 +# @brief used by the sublane model +LCA_SUBLANE = 1 << 15 +# @brief Vehicle is too slow to complete a continuous lane change (in case that maxSpeedLatStanding==0) +LCA_INSUFFICIENT_SPEED = 1 << 28 +# @brief lane can change +LCA_WANTS_LANECHANGE = LCA_LEFT | LCA_RIGHT +# @brief lane can change or stay +LCA_WANTS_LANECHANGE_OR_STAY = LCA_WANTS_LANECHANGE | LCA_STAY +# @brief blocked left +LCA_BLOCKED_LEFT = LCA_BLOCKED_BY_LEFT_LEADER | LCA_BLOCKED_BY_LEFT_FOLLOWER +# @brief blocked right +LCA_BLOCKED_RIGHT = LCA_BLOCKED_BY_RIGHT_LEADER | LCA_BLOCKED_BY_RIGHT_FOLLOWER +# @brief blocked by leader +LCA_BLOCKED_BY_LEADER = LCA_BLOCKED_BY_LEFT_LEADER | LCA_BLOCKED_BY_RIGHT_LEADER +# @brief blocker by follower +LCA_BLOCKED_BY_FOLLOWER = LCA_BLOCKED_BY_LEFT_FOLLOWER | LCA_BLOCKED_BY_RIGHT_FOLLOWER +# @brief blocked in all directions +LCA_BLOCKED = LCA_BLOCKED_LEFT | LCA_BLOCKED_RIGHT | LCA_INSUFFICIENT_SPACE | LCA_INSUFFICIENT_SPEED +# @brief reasons of lane change +LCA_CHANGE_REASONS = (LCA_STRATEGIC | LCA_COOPERATIVE | LCA_SPEEDGAIN | LCA_KEEPRIGHT | LCA_SUBLANE | LCA_TRACI) +# LCA_BLOCKED_BY_CURRENT_LEADER = 1 << 28 +# LCA_BLOCKED_BY_CURRENT_FOLLOWER = 1 << 29 +# @} + +# @name originally model specific states (migrated here since +# they were duplicated in all current models) +# @{ +LCA_AMBLOCKINGLEADER = 1 << 16 +LCA_AMBLOCKINGFOLLOWER = 1 << 17 +LCA_MRIGHT = 1 << 18 +LCA_MLEFT = 1 << 19 +# !!! never set LCA_UNBLOCK = 1 << 20, +LCA_AMBLOCKINGFOLLOWER_DONTBRAKE = 1 << 21 +# !!! never used LCA_AMBLOCKINGSECONDFOLLOWER = 1 << 22, +LCA_CHANGE_TO_HELP = 1 << 23 +# !!! never read LCA_KEEP1 = 1 << 24, +# !!! never used LCA_KEEP2 = 1 << 25, +LCA_AMBACKBLOCKER = 1 << 26 +LCA_AMBACKBLOCKER_STANDING = 1 << 27 +# @} diff --git a/co-simulation/traci_update/main.py b/co-simulation/traci_update/main.py new file mode 100644 index 00000000..33f2cb99 --- /dev/null +++ b/co-simulation/traci_update/main.py @@ -0,0 +1,326 @@ +# -*- coding: utf-8 -*- +# Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo +# Copyright (C) 2008-2022 German Aerospace Center (DLR) and others. +# This program and the accompanying materials are made available under the +# terms of the Eclipse Public License 2.0 which is available at +# https://www.eclipse.org/legal/epl-2.0/ +# This Source Code may also be made available under the following Secondary +# Licenses when the conditions for such availability set forth in the Eclipse +# Public License 2.0 are satisfied: GNU General Public License, version 2 +# or later which is available at +# https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html +# SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later + +# @file main.py +# @author Michael Behrisch +# @author Lena Kalleske +# @author Mario Krumnow +# @author Daniel Krajzewicz +# @author Jakob Erdmann +# @date 2008-10-09 + +# pylint: disable=E1101 + +from __future__ import print_function +from __future__ import absolute_import +import socket +import time +import subprocess +import warnings +import sys +import os +from functools import wraps + +if 'SUMO_HOME' in os.environ: + sys.path.append(os.path.join(os.environ['SUMO_HOME'], 'tools')) +else: + sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + +import sumolib # noqa +from sumolib.miscutils import getFreeSocketPort # noqa + +from .domain import _defaultDomains # noqa +# StepListener needs to be imported for backwards compatibility +from .connection import Connection, StepListener # noqa +from .exceptions import FatalTraCIError, TraCIException # noqa +from . import _inductionloop, _lanearea, _multientryexit, _trafficlight # noqa +from . import _variablespeedsign, _meandata # noqa +from . import _lane, _person, _route, _vehicle, _vehicletype # noqa +from . import _edge, _gui, _junction, _poi, _polygon, _simulation # noqa +from . import _calibrator, _routeprobe, _rerouter # noqa +from . import _busstop, _parkingarea, _chargingstation, _overheadwire # noqa +from . import constants as tc # noqa + +inductionloop = _inductionloop.InductionLoopDomain() +lanearea = _lanearea.LaneAreaDomain() +multientryexit = _multientryexit.MultiEntryExitDomain() +trafficlight = _trafficlight.TrafficLightDomain() +variablespeedsign = _variablespeedsign.VariableSpeedSignDomain() +meandata = _meandata.MeanDataDomain() +lane = _lane.LaneDomain() +person = _person.PersonDomain() +route = _route.RouteDomain() +vehicle = _vehicle.VehicleDomain() +vehicletype = _vehicletype.VehicleTypeDomain() +edge = _edge.EdgeDomain() +gui = _gui.GuiDomain() +junction = _junction.JunctionDomain() +poi = _poi.PoiDomain() +polygon = _polygon.PolygonDomain() +simulation = _simulation.SimulationDomain() +calibrator = _calibrator.CalibratorDomain() +busstop = _busstop.BusStopDomain() +parkingarea = _parkingarea.ParkingAreaDomain() +chargingstation = _chargingstation.ChargingStationDomain() +overheadwire = _overheadwire.OverheadWireDomain() +routeprobe = _routeprobe.RouteProbeDomain() +rerouter = _rerouter.RerouterDomain() + +_connections = {} +_traceFile = {} +_traceGetters = {} +# cannot use immutable type as global variable +_currentLabel = [""] +_connectHook = None + + +def _STEPS2TIME(step): + """Conversion from time steps in milliseconds to seconds as float""" + return step / 1000. + + +def setConnectHook(hookFunc): + global _connectHook + _connectHook = hookFunc + + +def _addTracing(method): + @wraps(method) + def tracingWrapper(*args, **kwargs): + _traceFile[_currentLabel[0]].write("traci.%s(%s)\n" % ( + method.__name__, + ', '.join(list(map(repr, args)) + ["%s=%s" % (n, repr(v)) for n, v in kwargs.items()]))) + return method(*args, **kwargs) + return tracingWrapper + + +def connect(port=8813, numRetries=tc.DEFAULT_NUM_RETRIES, host="localhost", proc=None, waitBetweenRetries=1): + """ + Establish a connection to a TraCI-Server and return the + connection object. The connection is not saved in the pool and not + accessible via traci.switch. It should be safe to use different + connections established by this method in different threads. + """ + for retry in range(1, numRetries + 2): + try: + conn = Connection(host, port, proc) + if _connectHook is not None: + _connectHook(conn) + return conn + except socket.error as e: + if proc is not None and proc.poll() is not None: + raise TraCIException("TraCI server already finished") + if retry > 1: + print("Could not connect to TraCI server at %s:%s" % (host, port), e) + if retry < numRetries + 1: + print(" Retrying in %s seconds" % waitBetweenRetries) + time.sleep(waitBetweenRetries) + raise FatalTraCIError("Could not connect in %s tries" % (numRetries + 1)) + +def getV2xMessage(): + if "" not in _connections: + raise FatalTraCIError("Not connected.") + return _connections[""].getV2xMessage() + +def setV2xMessage(message): + if "" not in _connections: + raise FatalTraCIError("Not connected.") + return _connections[""].setV2xMessage(message) + + +def init(port=8813, numRetries=tc.DEFAULT_NUM_RETRIES, host="localhost", label="default", proc=None, doSwitch=True): + """ + Establish a connection to a TraCI-Server and store it under the given + label. This method is not thread-safe. It accesses the connection + pool concurrently. + """ + _connections[label] = connect(port, numRetries, host, proc) + if doSwitch: + switch(label) + return _connections[label].getVersion() + + +def start(cmd, port=None, numRetries=tc.DEFAULT_NUM_RETRIES, label="default", verbose=False, + traceFile=None, traceGetters=True, stdout=None, doSwitch=True): + """ + Start a sumo server using cmd, establish a connection to it and + store it under the given label. This method is not thread-safe. + + - cmd (list): uses the Popen syntax. i.e. ['sumo', '-c', 'run.sumocfg']. The remote + port option will be added automatically + - numRetries (int): retries on failing to connect to sumo (more retries are needed + if a big .net.xml file must be loaded) + - label (string) : distinguish multiple traci connections used in the same script + - verbose (bool): print complete cmd + - traceFile (string): write all traci commands to FILE for debugging + - traceGetters (bool): whether to include get-commands in traceFile + - stdout (iostream): where to pipe sumo process stdout + """ + if label in _connections: + raise TraCIException("Connection '%s' is already active." % label) + if traceFile is not None: + _startTracing(traceFile, cmd, port, label, traceGetters) + while numRetries >= 0 and label not in _connections: + sumoPort = sumolib.miscutils.getFreeSocketPort() if port is None else port + cmd2 = cmd + ["--remote-port", str(sumoPort)] + if verbose: + print("Calling " + ' '.join(cmd2)) + sumoProcess = subprocess.Popen(cmd2, stdout=stdout) + try: + return init(sumoPort, numRetries, "localhost", label, sumoProcess, doSwitch) + except TraCIException as e: + if port is not None: + break + warnings.warn(("Could not connect to TraCI server using port %s (%s)." + + " Retrying with different port.") % (sumoPort, e)) + numRetries -= 1 + raise FatalTraCIError("Could not connect.") + + +def _startTracing(traceFile, cmd, port, label, traceGetters): + _traceFile[label] = open(traceFile, 'w') + _traceFile[label].write("traci.start(%s, port=%s, label=%s)\n" % ( + repr(cmd), repr(port), repr(label))) + _traceGetters[label] = traceGetters + + +def isLibsumo(): + return False + + +def isLibtraci(): + return False + + +def hasGUI(): + """ + Return whether a GUI and the corresponding GUI commands are available for the current connection. + """ + if "" not in _connections: + raise FatalTraCIError("Not connected.") + return _connections[""].hasGUI() + + +def load(args): + """load([optionOrParam, ...]) + Let sumo load a simulation using the given command line like options + Example: + load(['-c', 'run.sumocfg']) + load(['-n', 'net.net.xml', '-r', 'routes.rou.xml']) + """ + if "" not in _connections: + raise FatalTraCIError("Not connected.") + return _connections[""].load(args) + + +def isLoaded(): + return "" in _connections + + +def simulationStep(step=0): + """ + Make a simulation step and simulate up to the given second in sim time. + If the given value is 0 or absent, exactly one step is performed. + Values smaller than or equal to the current sim time result in no action. + """ + if "" not in _connections: + raise FatalTraCIError("Not connected.") + return _connections[""].simulationStep(step) + + +def addStepListener(listener): + """addStepListener(traci.StepListener) -> int + + Append the step listener (its step function is called at the end of every call to traci.simulationStep()) + to the current connection. + Returns the ID assigned to the listener if it was added successfully, None otherwise. + """ + if "" not in _connections: + raise FatalTraCIError("Not connected.") + return _connections[""].addStepListener(listener) + + +def removeStepListener(listenerID): + """removeStepListener(traci.StepListener) -> bool + + Remove the step listener from the current connection's step listener container. + Returns True if the listener was removed successfully, False if it wasn't registered. + """ + if "" not in _connections: + raise FatalTraCIError("Not connected.") + return _connections[""].removeStepListener(listenerID) + + +def getVersion(): + """getVersion() -> tuple + + Returns a tuple containing the TraCI API version number (integer) + and a string identifying the SUMO version running on the TraCI server in human-readable form. + """ + if "" not in _connections: + raise FatalTraCIError("Not connected.") + return _connections[""].getVersion() + + +def setOrder(order): + """ + Tells TraCI to give the current client the given position in the + execution order. It is mandatory to send this as the first command after + connecting to the TraCI server when using multiple clients. Each client + must be assigned a unique integer but there are not further restrictions + on numbering. + """ + if "" not in _connections: + raise FatalTraCIError("Not connected.") + return _connections[""].setOrder(order) + + +def close(wait=True): + """ + Tells TraCI to close the connection. + """ + if "" not in _connections: + raise FatalTraCIError("Not connected.") + _connections[""].close(wait) + _connections[""].simulation._setConnection(None) + del _connections[_currentLabel[0]] + del _connections[""] + if _currentLabel[0] in _traceFile: + del _traceFile[_currentLabel[0]] + + +def switch(label): + con = getConnection(label) + _connections[""] = con + _currentLabel[0] = label + for domain in _defaultDomains: + domain._setConnection(con) + if label in _traceFile: + domain._setTraceFile(_traceFile[label], _traceGetters[label]) + # connection holds a copy of each domain + getattr(con, domain._name)._setTraceFile(_traceFile[label], _traceGetters[label]) + con._traceFile = _traceFile[label] + + +def getLabel(): + return _currentLabel[0] + + +def getConnection(label="default"): + if label not in _connections: + raise TraCIException("Connection '%s' is not known." % label) + return _connections[label] + + +def setLegacyGetLeader(enabled): + _vehicle._legacyGetLeader = enabled diff --git a/docker-compose.yml b/docker-compose.yml deleted file mode 100644 index e6747418..00000000 --- a/docker-compose.yml +++ /dev/null @@ -1,40 +0,0 @@ -# Copyright (C) 2021 LEIDOS. -# -# 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. - -version: "2" -services: - co-simulation: - privileged: true - image: usdotfhwastol/carma-xil-cosimulation:latest - network_mode: host - environment: - - DISPLAY=${DISPLAY} - - QT_X11_NO_MITSHM=1 - volumes: - - /tmp/.X11-unix:/tmp/.X11-unix - deploy: - resources: - reservations: - devices: - - capabilities: [gpu] - command: bash -c "export NS3_HOME='/ns-3-integration/bin/fed/ns3' && cd /ns-3-integration/ && ./mosaic.sh -s ${map}_${vehicle_num}" - - carla-carma-integration: - image: usdotfhwastol/carla-carma-integration:latest - network_mode: host - environment: - - ROS_IP=127.0.0.1 - command: bash -c "sleep 10; export PYTHONPATH=$PYTHONPATH:/home/PythonAPI/carla-0.9.10-py2.7-linux-x86_64.egg && - source /home/carla_carma_ws/devel/setup.bash && - roslaunch carla_carma_agent carla_carma_agent.launch town:=${map}" diff --git a/docker/build-image.sh b/docker/build-image.sh index 30ebb9d0..8df3486d 100755 --- a/docker/build-image.sh +++ b/docker/build-image.sh @@ -1,13 +1,13 @@ #!/bin/bash # Copyright (C) 2018-2020 LEIDOS. -# +# # 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 @@ -17,7 +17,8 @@ USERNAME=usdotfhwastol cd "$(dirname "$0")" -IMAGE=$(./get-image-name.sh | tr '[:upper:]' '[:lower:]') +# IMAGE=$(./get-image-name.sh | tr '[:upper:]' '[:lower:]') +IMAGE="carma-xil-cosimulation" echo "" echo "##### $IMAGE Docker Image Build Script #####" diff --git a/docker/run.sh b/docker/run.sh new file mode 100755 index 00000000..5aa8d232 --- /dev/null +++ b/docker/run.sh @@ -0,0 +1,30 @@ +#!/bin/bash + +RUNTIME="" +IMAGE="carma-xil-cosimulation" +DOCKER_VERSION=$(docker version --format '{{.Client.Version}}' | cut --delimiter=. --fields=1,2) +if [[ $DOCKER_VERSION < "19.03" ]] && ! type nvidia-docker; then + RUNTIME="--gpus all" +else + RUNTIME="--runtime=nvidia" +fi + +while [[ $# -gt 0 ]]; do + arg="$1" + case $arg in + -v|--version) + COMPONENT_VERSION_STRING="$2" + shift + shift + ;; + esac +done +echo "##### Running usdotfhwastol/carma-xil-cosimulation:$COMPONENT_VERSION_STRING docker container #####" +docker run \ + --rm -it\ + --gpus all\ + --net=host\ + -v /tmp/.X11-unix:/tmp/.X11-unix\ + -e DISPLAY=$DISPLAY\ + -e QT_X11_NO_MITSHM=1\ + --user=carla_sumo_mosaic usdotfhwastol/carma-xil-cosimulation:$COMPONENT_VERSION_STRING