CARLA
Loading...
Searching...
No Matches
TrafficManager.cpp
Go to the documentation of this file.
1// Copyright (c) 2026 Computer Vision Center (CVC) at the Universitat Autonoma
2// de Barcelona (UAB).
3//
4// This work is licensed under the terms of the MIT license.
5// For a copy, see <https://opensource.org/licenses/MIT>.
6
7//#include "carla/client/Client.h"
8
9
10#include "carla/Sockets.h"
12
18
19#include "carla/Logging.h"
20
21#include <condition_variable>
22#include <deque>
23#include <exception>
24#include <thread>
25#include <utility>
26
27#ifndef _WIN32
28#include <unistd.h>
29#endif
30
31#define DEBUG_PRINT_TM 0
32#define IP_DATA_BUFFER_SIZE 80
33
34namespace carla {
35namespace traffic_manager {
36
37using namespace constants::SpeedThreshold;
38using namespace constants::PID;
39
40std::map<uint16_t, TrafficManagerBase*> TrafficManager::_tm_map;
41std::mutex TrafficManager::_mutex;
42
45 uint16_t port)
46 : _port(port) {
47
48 if(!GetTM(_port)){
49 // Check if a TM server already exists and connect to it
50 if(!CreateTrafficManagerClient(episode_proxy, port)) {
51 // As TM server not running, create one
52 CreateTrafficManagerServer(episode_proxy, port);
53 }
54 }
55}
56
57// Released vehicles and deleted TMs are dropped after unlocking _mutex: they may destroy a client.
58
59static void AppendReleased(std::vector<ActorPtr> &out, TrafficManagerBase &tm) {
60 auto released = tm.TakeReleasedActors();
61 out.insert(out.end(),
62 std::make_move_iterator(released.begin()),
63 std::make_move_iterator(released.end()));
64}
65
67 std::vector<ActorPtr> released;
68 std::vector<TrafficManagerBase *> to_delete;
69 {
70 std::scoped_lock<std::mutex> lock(_mutex);
71 for(auto& tm : _tm_map) {
72 tm.second->Release();
73 AppendReleased(released, *tm.second);
74 to_delete.push_back(tm.second);
75 }
76 _tm_map.clear();
77 }
78 for (auto *tm_ptr : to_delete) {
79 delete tm_ptr;
80 }
81}
82
83void TrafficManager::Reset(uint64_t episode_id) {
84 std::vector<ActorPtr> released;
85 {
86 std::scoped_lock<std::mutex> lock(_mutex);
87 for(auto& tm : _tm_map) {
88 tm.second->Reset(episode_id);
89 AppendReleased(released, *tm.second);
90 }
91 }
92}
93
95 std::vector<ActorPtr> released;
96 {
97 std::scoped_lock<std::mutex> lock(_mutex);
98 for(auto& tm : _tm_map) {
99 tm.second->SynchronousTick();
100 AppendReleased(released, *tm.second);
101 }
102 }
103}
104
106 TrafficManagerBase* tm_ptr = nullptr;
107 std::vector<ActorPtr> released;
108 {
109 std::scoped_lock<std::mutex> lock(_mutex);
110 auto it = _tm_map.find(_port);
111 if (it != _tm_map.end()) {
112 tm_ptr = it->second;
113 _tm_map.erase(it);
114 }
115 if(tm_ptr != nullptr) {
116 tm_ptr->ShutDown();
117 AppendReleased(released, *tm_ptr);
118 }
119 }
120 delete tm_ptr;
121}
122
123namespace {
124
125 /// Resets the TMs on an episode change; owned by no client, so it never joins itself.
126 class EpisodeResetThread {
127 public:
128
129 void Post(uint64_t episode_id, std::function<void()> on_done) {
130 std::unique_lock<std::mutex> lock(_mutex);
131 _queue.emplace_back(episode_id, std::move(on_done));
132 // A forked child inherits _running but not the thread.
133 if (!_running || _owner != CurrentProcess()) {
134 _running = true;
135 _owner = CurrentProcess();
136 std::thread(&EpisodeResetThread::Run, this).detach();
137 }
138 _cv.notify_all();
139 }
140
141 private:
142
143 static long CurrentProcess() {
144#ifdef _WIN32
145 return 0;
146#else
147 return static_cast<long>(::getpid());
148#endif
149 }
150
151 void Run() {
152 std::unique_lock<std::mutex> lock(_mutex);
153 while (true) {
154 _cv.wait(lock, [this]() { return !_queue.empty(); });
155 auto item = std::move(_queue.front());
156 _queue.pop_front();
157 const bool reset = !_has_last || item.first != _last_episode_id;
158 _last_episode_id = item.first;
159 _has_last = true;
160 lock.unlock();
161 if (reset) {
162 try {
163 TrafficManager::Reset(item.first);
164 } catch (const std::exception &e) {
165 log_error("failed to reset the Traffic Manager for the new episode:", e.what());
166 }
167 }
168 if (item.second) {
169 item.second();
170 }
171 // Drop the callback before re-locking.
172 item = {};
173 lock.lock();
174 }
175 }
176
177 std::mutex _mutex;
178 std::condition_variable _cv;
179 std::deque<std::pair<uint64_t, std::function<void()>>> _queue;
180 uint64_t _last_episode_id = 0u;
181 bool _has_last = false;
182 bool _running = false;
183 long _owner = 0;
184 };
185
186 EpisodeResetThread &GetEpisodeResetThread() {
187 // Never destroyed: the detached thread may outlive static destruction at exit.
188 static EpisodeResetThread *instance = new EpisodeResetThread();
189 return *instance;
190 }
191
192} // namespace
193
194void TrafficManager::RequestReset(uint64_t episode_id, std::function<void()> on_done) {
195 GetEpisodeResetThread().Post(episode_id, std::move(on_done));
196}
197
200 uint16_t port) {
201
202 // Get local IP details.
203 auto GetLocalIP = [=](const uint16_t sport)-> std::pair<std::string, uint16_t> {
204 std::pair<std::string, uint16_t> localIP;
205 int sock = socket(AF_INET, SOCK_DGRAM, 0);
206 if(sock == SOCK_INVALID_INDEX) {
207 #if DEBUG_PRINT_TM
208 std::cout << "Error number 1: " << errno << std::endl;
209 std::cout << "Error message: " << strerror(errno) << std::endl;
210 #endif
211 } else {
212 int err;
213 sockaddr_in loopback;
214 std::memset(&loopback, 0, sizeof(loopback));
215 loopback.sin_family = AF_INET;
216 loopback.sin_addr.s_addr = INADDR_LOOPBACK;
217 loopback.sin_port = htons(9);
218 err = connect(sock, reinterpret_cast<sockaddr*>(&loopback), sizeof(loopback));
219 if(err == SOCK_INVALID_INDEX) {
220 #if DEBUG_PRINT_TM
221 std::cout << "Error number 2: " << errno << std::endl;
222 std::cout << "Error message: " << strerror(errno) << std::endl;
223 #endif
224 } else {
225 socklen_t addrlen = sizeof(loopback);
226 err = getsockname(sock, reinterpret_cast<struct sockaddr*> (&loopback), &addrlen);
227 if(err == SOCK_INVALID_INDEX) {
228 #if DEBUG_PRINT_TM
229 std::cout << "Error number 3: " << errno << std::endl;
230 std::cout << "Error message: " << strerror(errno) << std::endl;
231 #endif
232 } else {
233 char buffer[IP_DATA_BUFFER_SIZE];
234 const char* p = inet_ntop(AF_INET, &loopback.sin_addr, buffer, IP_DATA_BUFFER_SIZE);
235 if(p != NULL) {
236 localIP = std::pair<std::string, uint16_t>(std::string(buffer), sport);
237 } else {
238 #if DEBUG_PRINT_TM
239 std::cout << "Error number 4: " << errno << std::endl;
240 std::cout << "Error message: " << strerror(errno) << std::endl;
241 #endif
242 }
243 }
244 }
245 #ifdef _WIN32
246 closesocket(sock);
247 #else
248 close(sock);
249 #endif
250 }
251 return localIP;
252 };
253
254 /// Define local constants
255 const std::vector<float> longitudinal_param = LONGITUDIAL_PARAM;
256 const std::vector<float> longitudinal_highway_param = LONGITUDIAL_HIGHWAY_PARAM;
257 const std::vector<float> lateral_param = LATERAL_PARAM;
258 const std::vector<float> lateral_highway_param = LATERAL_HIGHWAY_PARAM;
259 const float perc_difference_from_limit = INITIAL_PERCENTAGE_SPEED_DIFFERENCE;
260
261 std::pair<std::string, uint16_t> serverTM;
262
263 /// Create local instance of TM
265 longitudinal_param,
266 longitudinal_highway_param,
267 lateral_param,
268 lateral_highway_param,
269 perc_difference_from_limit,
270 episode_proxy,
271 port);
272
273 /// Get TM server info (Local IP & PORT)
274 serverTM = GetLocalIP(port);
275
276 /// Set this client as the TM to server
277 episode_proxy.Lock()->AddTrafficManagerRunning(serverTM);
278
279 #if DEBUG_PRINT_TM
280 /// Print status
281 std::cout << "NEW@: Registered TM at "
282 << serverTM.first << ":"
283 << serverTM.second << " ..... SUCCESS."
284 << std::endl;
285 #endif
286
287 /// Set the pointer of the instance
288 _tm_map.insert(std::make_pair(port, tm_ptr));
289
290}
291
294 uint16_t port) {
295
296 bool result = false;
297
298 if(episode_proxy.Lock()->IsTrafficManagerRunning(port)) {
299
300 /// Get TM server info (Remote IP & PORT)
301 std::pair<std::string, uint16_t> serverTM =
302 episode_proxy.Lock()->GetTrafficManagerRunning(port);
303
304 /// Set remote TM server IP and port
305 TrafficManagerRemote* tm_ptr = new(std::nothrow)
306 TrafficManagerRemote(serverTM, episode_proxy);
307
308 /// Try to connect to remote TM server
309 try {
310
311 /// Check memory allocated or not
312 if(tm_ptr != nullptr) {
313
314 #if DEBUG_PRINT_TM
315 // Test print
316 std::cout << "OLD@: Registered TM at "
317 << serverTM.first << ":"
318 << serverTM.second << " ..... TRY "
319 << std::endl;
320 #endif
321 /// Try to reset all traffic lights
322 tm_ptr->HealthCheckRemoteTM();
323
324 /// Set the pointer of the instance
325 _tm_map.insert(std::make_pair(port, tm_ptr));
326
327 result = true;
328 }
329 }
330
331 /// If Connection error occurred
332 catch (...) {
333
334 /// Clear previously allocated memory
335 delete tm_ptr;
336
337 #if DEBUG_PRINT_TM
338 /// Test print
339 std::cout << "OLD@: Registered TM at "
340 << serverTM.first << ":"
341 << serverTM.second << " ..... FAILED "
342 << std::endl;
343 #endif
344 }
345
346 }
347
348 return result;
349}
350
351} // namespace traffic_manager
352} // namespace carla
#define SOCK_INVALID_INDEX
< socket sockaddr_in getsockname
Definition Sockets.h:24
#define IP_DATA_BUFFER_SIZE
SharedPtrType Lock() const
Same as TryLock but never return nullptr.
The function of this class is to integrate all the various stages of the traffic manager appropriatel...
virtual std::vector< ActorPtr > TakeReleasedActors()
Vehicles released since the last call; the caller drops them with no TM lock held.
The function of this class is to integrate all the various stages of the traffic manager appropriatel...
TrafficManagerLocal(std::vector< float > longitudinal_PID_parameters, std::vector< float > longitudinal_highway_PID_parameters, std::vector< float > lateral_PID_parameters, std::vector< float > lateral_highway_PID_parameters, float perc_decrease_from_limit, cc::detail::EpisodeProxy &episode_proxy, uint16_t &RPCportTM)
Private constructor for singleton lifecycle management.
The function of this class is to integrate all the various stages of the traffic manager appropriatel...
TrafficManagerRemote(const std::pair< std::string, uint16_t > &_serverTM, carla::client::detail::EpisodeProxy &episodeProxy)
Constructor store remote location information.
void HealthCheckRemoteTM()
Method to check server is alive or not.
static std::map< uint16_t, TrafficManagerBase * > _tm_map
static void RequestReset(uint64_t episode_id, std::function< void()> on_done)
Non-blocking: reset all TMs once per episode on the reset thread, then call on_done.
TrafficManagerBase * GetTM(uint16_t port) const
void CreateTrafficManagerServer(carla::client::detail::EpisodeProxy episode_proxy, uint16_t port)
bool CreateTrafficManagerClient(carla::client::detail::EpisodeProxy episode_proxy, uint16_t port)
static void Reset(uint64_t episode_id)
EpisodeProxyImpl< EpisodeProxyPointerType::Strong > EpisodeProxy
static void AppendReleased(std::vector< ActorPtr > &out, TrafficManagerBase &tm)
This file contains definitions of common data structures used in traffic manager.