simulation_world_updater.cc 13.4 KB
Newer Older
S
siyangy 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
/******************************************************************************
 * Copyright 2017 The Apollo Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *****************************************************************************/

17
#include "modules/dreamview/backend/simulation_world/simulation_world_updater.h"
S
siyangy 已提交
18

S
siyangy 已提交
19
#include "google/protobuf/util/json_util.h"
20
#include "modules/common/util/json_util.h"
21
#include "modules/common/util/map_util.h"
22
#include "modules/dreamview/backend/common/dreamview_gflags.h"
23
#include "modules/map/hdmap/hdmap_util.h"
S
siyangy 已提交
24 25 26 27

namespace apollo {
namespace dreamview {

S
siyangy 已提交
28
using apollo::common::adapter::AdapterManager;
29
using apollo::common::monitor::MonitorMessageItem;
30
using apollo::common::util::ContainsKey;
31 32
using apollo::common::util::GetProtoFromASCIIFile;
using apollo::common::util::JsonUtil;
33
using apollo::hdmap::EndWayPointFile;
34
using apollo::routing::RoutingRequest;
S
siyangy 已提交
35
using Json = nlohmann::json;
S
siyangy 已提交
36 37
using google::protobuf::util::JsonStringToMessage;
using google::protobuf::util::MessageToJsonString;
S
siyangy 已提交
38

39
SimulationWorldUpdater::SimulationWorldUpdater(WebSocketHandler *websocket,
40
                                               WebSocketHandler *map_ws,
S
siyangy 已提交
41
                                               SimControl *sim_control,
42
                                               const MapService *map_service,
S
siyangy 已提交
43 44
                                               bool routing_from_file)
    : sim_world_service_(map_service, routing_from_file),
45
      map_service_(map_service),
S
siyangy 已提交
46
      websocket_(websocket),
S
siyangy 已提交
47
      map_ws_(map_ws),
S
siyangy 已提交
48
      sim_control_(sim_control) {
49 50 51 52
  RegisterMessageHandlers();
}

void SimulationWorldUpdater::RegisterMessageHandlers() {
53 54 55 56 57 58 59 60
  // Send current sim_control status to the new client.
  websocket_->RegisterConnectionReadyHandler(
      [this](WebSocketHandler::Connection *conn) {
        Json response;
        response["type"] = "SimControlStatus";
        response["enabled"] = sim_control_->IsEnabled();
        websocket_->SendData(conn, response.dump());
      });
V
vlin17 已提交
61

62
  map_ws_->RegisterMessageHandler(
S
siyangy 已提交
63 64 65 66
      "RetrieveMapData",
      [this](const Json &json, WebSocketHandler::Connection *conn) {
        auto iter = json.find("elements");
        if (iter != json.end()) {
S
siyangy 已提交
67 68 69
          MapElementIds map_element_ids;
          if (JsonStringToMessage(iter->dump(), &map_element_ids).ok()) {
            auto retrieved = map_service_->RetrieveMapElements(map_element_ids);
70 71 72 73 74

            std::string retrieved_map_string;
            retrieved.SerializeToString(&retrieved_map_string);

            map_ws_->SendBinaryData(conn, retrieved_map_string, true);
S
siyangy 已提交
75 76 77
          } else {
            AERROR << "Failed to parse MapElementIds from json";
          }
S
siyangy 已提交
78 79
        }
      });
80

V
vlin17 已提交
81 82 83
  map_ws_->RegisterMessageHandler(
      "RetrieveRelativeMapData",
      [this](const Json &json, WebSocketHandler::Connection *conn) {
S
siyangy 已提交
84 85 86 87 88 89
        std::string to_send;
        {
          boost::shared_lock<boost::shared_mutex> reader_lock(mutex_);
          to_send = relative_map_string_;
        }
        map_ws_->SendBinaryData(conn, to_send, true);
V
vlin17 已提交
90 91
      });

V
vlin17 已提交
92 93
  websocket_->RegisterMessageHandler(
      "Binary",
94
      [this](const std::string &data, WebSocketHandler::Connection *conn) {
V
vlin17 已提交
95 96 97 98 99 100 101 102 103 104 105
        apollo::relative_map::NavigationInfo navigation_info;
        if (navigation_info.ParseFromString(data)) {
          AdapterManager::FillNavigationHeader(FLAGS_dreamview_module_name,
                                               &navigation_info);
          AdapterManager::PublishNavigation(navigation_info);
        } else {
          AERROR << "Failed to parse navigation info from string. String size: "
                 << data.size();
        }
      });

106
  websocket_->RegisterMessageHandler(
S
siyangy 已提交
107
      "RetrieveMapElementIdsByRadius",
108 109 110
      [this](const Json &json, WebSocketHandler::Connection *conn) {
        auto radius = json.find("radius");
        if (radius == json.end()) {
111
          AERROR << "Cannot retrieve map elements with unknown radius.";
112
          return;
113 114
        }

115 116 117 118 119 120
        if (!radius->is_number()) {
          AERROR << "Expect radius with type 'number', but was "
                 << radius->type_name();
          return;
        }

S
siyangy 已提交
121 122 123 124 125 126 127 128 129 130
        Json response;
        response["type"] = "MapElementIds";
        response["mapRadius"] = *radius;

        MapElementIds ids;
        sim_world_service_.GetMapElementIds(*radius, &ids);
        std::string elementIds;
        MessageToJsonString(ids, &elementIds);
        response["mapElementIds"] = Json::parse(elementIds);

131
        websocket_->SendData(conn, response.dump());
132 133
      });

134 135 136
  websocket_->RegisterMessageHandler(
      "SendRoutingRequest",
      [this](const Json &json, WebSocketHandler::Connection *conn) {
137
        RoutingRequest routing_request;
138

139 140 141 142 143 144 145
        bool succeed = ConstructRoutingRequest(json, &routing_request);
        if (succeed) {
          AdapterManager::FillRoutingRequestHeader(FLAGS_dreamview_module_name,
                                                   &routing_request);
          AdapterManager::PublishRoutingRequest(routing_request);
        }

146
        // Publish monitor message.
147
        if (succeed) {
148
          sim_world_service_.PublishMonitorMessage(MonitorMessageItem::INFO,
A
Aaron Xiao 已提交
149
                                                   "Routing request Sent");
150
        } else {
S
siyangy 已提交
151 152
          sim_world_service_.PublishMonitorMessage(
              MonitorMessageItem::ERROR, "Failed to send routing request");
153
        }
154
      });
155 156

  websocket_->RegisterMessageHandler(
157 158
      "RequestSimulationWorld",
      [this](const Json &json, WebSocketHandler::Connection *conn) {
159 160 161 162 163 164
        if (!sim_world_service_.ReadyToPush()) {
          AWARN_EVERY(100)
              << "Not sending simulation world as the data is not ready!";
          return;
        }

165
        bool enable_pnc_monitor = false;
166 167
        auto planning = json.find("planning");
        if (planning != json.end() && planning->is_boolean()) {
168
          enable_pnc_monitor = json["planning"];
169
        }
170 171 172 173 174
        std::string to_send;
        {
          // Pay the price to copy the data instead of sending data over the
          // wire while holding the lock.
          boost::shared_lock<boost::shared_mutex> reader_lock(mutex_);
175 176
          to_send = enable_pnc_monitor ? simulation_world_with_planning_data_
                                       : simulation_world_;
177
        }
178
        if (FLAGS_enable_update_size_check && !enable_pnc_monitor &&
179 180 181 182
            to_send.size() > FLAGS_max_update_size) {
          AWARN << "update size is too big:" << to_send.size();
          return;
        }
S
siyangy 已提交
183
        websocket_->SendBinaryData(conn, to_send, true);
184
      });
185

S
siyangy 已提交
186 187 188 189 190 191 192 193
  websocket_->RegisterMessageHandler(
      "RequestRoutePath",
      [this](const Json &json, WebSocketHandler::Connection *conn) {
        Json response = sim_world_service_.GetRoutePathAsJson();
        response["type"] = "RoutePath";
        websocket_->SendData(conn, response.dump());
      });

194 195 196 197 198 199
  websocket_->RegisterMessageHandler(
      "GetDefaultEndPoint",
      [this](const Json &json, WebSocketHandler::Connection *conn) {
        Json response;
        response["type"] = "DefaultEndPoint";

200 201
        Json poi_list = Json::array();
        if (LoadPOI()) {
S
siyangy 已提交
202
          for (const auto &landmark : poi_.landmark()) {
203 204
            Json place;
            place["name"] = landmark.name();
205 206 207 208 209 210 211 212
            Json waypoint_list;
            for (const auto &waypoint : landmark.waypoint()) {
              Json point;
              point["x"] = waypoint.pose().x();
              point["y"] = waypoint.pose().y();
              waypoint_list.push_back(point);
            }
            place["waypoint"] = waypoint_list;
213 214
            poi_list.push_back(place);
          }
215
        } else {
S
siyangy 已提交
216 217 218 219 220
          sim_world_service_.PublishMonitorMessage(MonitorMessageItem::ERROR,
                                                   "Failed to load default "
                                                   "POI. Please make sure the "
                                                   "file exists at " +
                                                       EndWayPointFile());
221
        }
222
        response["poi"] = poi_list;
223 224
        websocket_->SendData(conn, response.dump());
      });
S
siyangy 已提交
225 226 227 228

  websocket_->RegisterMessageHandler(
      "Reset", [this](const Json &json, WebSocketHandler::Connection *conn) {
        sim_world_service_.SetToClear();
S
siyangy 已提交
229
        sim_control_->Reset();
S
siyangy 已提交
230
      });
S
siyangy 已提交
231 232 233 234 235

  websocket_->RegisterMessageHandler(
      "Dump", [this](const Json &json, WebSocketHandler::Connection *conn) {
        DumpMessage(AdapterManager::GetChassis(), "Chassis");
        DumpMessage(AdapterManager::GetPrediction(), "Prediction");
236
        DumpMessage(AdapterManager::GetRoutingRequest(), "RoutingRequest");
S
siyangy 已提交
237 238 239
        DumpMessage(AdapterManager::GetRoutingResponse(), "RoutingResponse");
        DumpMessage(AdapterManager::GetLocalization(), "Localization");
        DumpMessage(AdapterManager::GetPlanning(), "Planning");
240 241 242 243 244
        DumpMessage(AdapterManager::GetControlCommand(), "Control");
        DumpMessage(AdapterManager::GetPerceptionObstacles(), "Perception");
        DumpMessage(AdapterManager::GetTrafficLightDetection(), "TrafficLight");
        DumpMessage(AdapterManager::GetRelativeMap(), "RelativeMap");
        DumpMessage(AdapterManager::GetNavigation(), "Navigation");
245 246
        DumpMessage(AdapterManager::GetContiRadar(), "ContiRadar");
        DumpMessage(AdapterManager::GetMobileye(), "Mobileye");
S
siyangy 已提交
247
      });
S
siyangy 已提交
248 249 250 251 252 253 254 255 256 257 258 259 260

  websocket_->RegisterMessageHandler(
      "ToggleSimControl",
      [this](const Json &json, WebSocketHandler::Connection *conn) {
        auto enable = json.find("enable");
        if (enable != json.end() && enable->is_boolean()) {
          if (*enable) {
            sim_control_->Start();
          } else {
            sim_control_->Stop();
          }
        }
      });
261 262 263
}

bool SimulationWorldUpdater::ConstructRoutingRequest(
S
siyangy 已提交
264
    const Json &json, RoutingRequest *routing_request) {
265 266
  routing_request->clear_waypoint();
  // set start point
267
  if (!ContainsKey(json, "start")) {
268
    AERROR << "Failed to prepare a routing request: start point not found.";
269 270 271
    return false;
  }

272
  auto start = json["start"];
273 274 275 276 277 278 279 280
  if (!ValidateCoordinate(start)) {
    AERROR << "Failed to prepare a routing request: invalid start point.";
    return false;
  }
  if (!map_service_->ConstructLaneWayPoint(start["x"], start["y"],
                                           routing_request->add_waypoint())) {
    AERROR << "Failed to prepare a routing request:"
           << " cannot locate start point on map.";
281 282 283 284 285
    return false;
  }

  // set way point(s) if any
  auto iter = json.find("waypoint");
286
  if (iter != json.end() && iter->is_array()) {
S
siyangy 已提交
287
    auto *waypoint = routing_request->mutable_waypoint();
288
    for (size_t i = 0; i < iter->size(); ++i) {
S
siyangy 已提交
289
      auto &point = (*iter)[i];
290 291
      if (!ValidateCoordinate(point)) {
        AERROR << "Failed to prepare a routing request: invalid waypoint.";
S
siyangy 已提交
292 293 294
        return false;
      }

295 296 297 298 299 300 301 302
      if (!map_service_->ConstructLaneWayPoint(point["x"], point["y"],
                                               waypoint->Add())) {
        waypoint->RemoveLast();
      }
    }
  }

  // set end point
303
  if (!ContainsKey(json, "end")) {
304
    AERROR << "Failed to prepare a routing request: end point not found.";
305 306
    return false;
  }
307

308
  auto end = json["end"];
309 310 311 312 313 314 315 316
  if (!ValidateCoordinate(end)) {
    AERROR << "Failed to prepare a routing request: invalid end point.";
    return false;
  }
  if (!map_service_->ConstructLaneWayPoint(end["x"], end["y"],
                                           routing_request->add_waypoint())) {
    AERROR << "Failed to prepare a routing request:"
           << " cannot locate end point on map.";
317
    return false;
318 319
  }

320
  AINFO << "Constructed RoutingRequest to be sent:\n"
S
siyangy 已提交
321
        << routing_request->DebugString();
322

323
  return true;
S
siyangy 已提交
324 325
}

326 327 328 329 330 331 332 333 334 335 336 337
bool SimulationWorldUpdater::ValidateCoordinate(const nlohmann::json &json) {
  if (!ContainsKey(json, "x") || !ContainsKey(json, "y")) {
    AERROR << "Failed to find x or y coordinate.";
    return false;
  }
  if (json.find("x")->is_number() && json.find("y")->is_number()) {
    return true;
  }
  AERROR << "Both x and y coordinate should be a number.";
  return false;
}

S
siyangy 已提交
338 339
void SimulationWorldUpdater::Start() {
  // start ROS timer, one-shot = false, auto-start = true
S
siyangy 已提交
340 341 342
  timer_ =
      AdapterManager::CreateTimer(ros::Duration(kSimWorldTimeIntervalMs / 1000),
                                  &SimulationWorldUpdater::OnTimer, this);
S
siyangy 已提交
343 344
}

345
void SimulationWorldUpdater::OnTimer(const ros::TimerEvent &event) {
S
siyangy 已提交
346
  sim_world_service_.Update();
347 348 349

  {
    boost::unique_lock<boost::shared_mutex> writer_lock(mutex_);
350 351 352
    sim_world_service_.GetWireFormatString(
        FLAGS_sim_map_radius, &simulation_world_,
        &simulation_world_with_planning_data_);
S
siyangy 已提交
353 354
    sim_world_service_.GetRelativeMap().SerializeToString(
        &relative_map_string_);
355
  }
S
siyangy 已提交
356 357
}

358
bool SimulationWorldUpdater::LoadPOI() {
359
  if (GetProtoFromASCIIFile(EndWayPointFile(), &poi_)) {
360
    return true;
361
  }
362

363
  AWARN << "Failed to load default list of POI from " << EndWayPointFile();
364
  return false;
365 366
}

S
siyangy 已提交
367 368
}  // namespace dreamview
}  // namespace apollo