simulation_world_updater.cc 15.2 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

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

namespace apollo {
namespace dreamview {

29
using apollo::common::monitor::MonitorMessageItem;
30
using apollo::common::util::ContainsKey;
X
 
Xiangquan Xiao 已提交
31
using apollo::cyber::common::GetProtoFromASCIIFile;
32
using apollo::hdmap::EndWayPointFile;
33
using apollo::relative_map::NavigationInfo;
34
using apollo::routing::RoutingRequest;
35

S
siyangy 已提交
36
using Json = nlohmann::json;
S
siyangy 已提交
37 38
using google::protobuf::util::JsonStringToMessage;
using google::protobuf::util::MessageToJsonString;
S
siyangy 已提交
39

V
vlin17 已提交
40 41
SimulationWorldUpdater::SimulationWorldUpdater(
    WebSocketHandler *websocket, WebSocketHandler *map_ws,
42 43 44 45
    WebSocketHandler *camera_ws, SimControl *sim_control,
    const MapService *map_service,
    DataCollectionMonitor *data_collection_monitor,
    PerceptionCameraUpdater *perception_camera_updater, bool routing_from_file)
S
siyangy 已提交
46
    : sim_world_service_(map_service, routing_from_file),
47
      map_service_(map_service),
S
siyangy 已提交
48
      websocket_(websocket),
S
siyangy 已提交
49
      map_ws_(map_ws),
50
      camera_ws_(camera_ws),
V
vlin17 已提交
51
      sim_control_(sim_control),
52 53
      data_collection_monitor_(data_collection_monitor),
      perception_camera_updater_(perception_camera_updater) {
54 55 56 57
  RegisterMessageHandlers();
}

void SimulationWorldUpdater::RegisterMessageHandlers() {
58 59 60 61 62 63 64 65
  // 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 已提交
66

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

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

            map_ws_->SendBinaryData(conn, retrieved_map_string, true);
S
siyangy 已提交
80 81 82
          } else {
            AERROR << "Failed to parse MapElementIds from json";
          }
S
siyangy 已提交
83 84
        }
      });
85

V
vlin17 已提交
86 87 88
  map_ws_->RegisterMessageHandler(
      "RetrieveRelativeMapData",
      [this](const Json &json, WebSocketHandler::Connection *conn) {
S
siyangy 已提交
89 90 91 92 93 94
        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 已提交
95 96
      });

V
vlin17 已提交
97 98
  websocket_->RegisterMessageHandler(
      "Binary",
99
      [this](const std::string &data, WebSocketHandler::Connection *conn) {
S
siyangy 已提交
100
        // Navigation info in binary format
101
        auto navigation_info = std::make_shared<NavigationInfo>();
102 103
        if (navigation_info->ParseFromString(data)) {
          sim_world_service_.PublishNavigationInfo(navigation_info);
V
vlin17 已提交
104 105 106 107 108 109
        } else {
          AERROR << "Failed to parse navigation info from string. String size: "
                 << data.size();
        }
      });

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

119 120 121 122 123 124
        if (!radius->is_number()) {
          AERROR << "Expect radius with type 'number', but was "
                 << radius->type_name();
          return;
        }

S
siyangy 已提交
125 126 127 128 129 130 131 132 133 134
        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);

135
        websocket_->SendData(conn, response.dump());
136 137
      });

138 139 140 141 142 143 144 145
  websocket_->RegisterMessageHandler(
      "CheckRoutingPoint",
      [this](const Json &json, WebSocketHandler::Connection *conn) {
        Json response = CheckRoutingPoint(json);
        response["type"] = "RoutingPointCheckResult";
        websocket_->SendData(conn, response.dump());
      });

146 147 148
  websocket_->RegisterMessageHandler(
      "SendRoutingRequest",
      [this](const Json &json, WebSocketHandler::Connection *conn) {
149
        auto routing_request = std::make_shared<RoutingRequest>();
150

151
        bool succeed = ConstructRoutingRequest(json, routing_request.get());
152
        if (succeed) {
153
          sim_world_service_.PublishRoutingRequest(routing_request);
154
          sim_world_service_.PublishMonitorMessage(MonitorMessageItem::INFO,
V
vlin17 已提交
155
                                                   "Routing request sent.");
156
        } else {
S
siyangy 已提交
157
          sim_world_service_.PublishMonitorMessage(
V
vlin17 已提交
158
              MonitorMessageItem::ERROR, "Failed to send a routing request.");
159
        }
160
      });
161 162

  websocket_->RegisterMessageHandler(
163 164
      "RequestSimulationWorld",
      [this](const Json &json, WebSocketHandler::Connection *conn) {
165 166 167 168 169 170
        if (!sim_world_service_.ReadyToPush()) {
          AWARN_EVERY(100)
              << "Not sending simulation world as the data is not ready!";
          return;
        }

171
        bool enable_pnc_monitor = false;
172 173
        auto planning = json.find("planning");
        if (planning != json.end() && planning->is_boolean()) {
174
          enable_pnc_monitor = json["planning"];
175
        }
176 177 178 179 180
        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_);
181 182
          to_send = enable_pnc_monitor ? simulation_world_with_planning_data_
                                       : simulation_world_;
183
        }
184
        if (FLAGS_enable_update_size_check && !enable_pnc_monitor &&
185 186 187 188
            to_send.size() > FLAGS_max_update_size) {
          AWARN << "update size is too big:" << to_send.size();
          return;
        }
S
siyangy 已提交
189
        websocket_->SendBinaryData(conn, to_send, true);
190
      });
191

S
siyangy 已提交
192 193 194 195 196 197 198 199
  websocket_->RegisterMessageHandler(
      "RequestRoutePath",
      [this](const Json &json, WebSocketHandler::Connection *conn) {
        Json response = sim_world_service_.GetRoutePathAsJson();
        response["type"] = "RoutePath";
        websocket_->SendData(conn, response.dump());
      });

200 201 202 203 204 205
  websocket_->RegisterMessageHandler(
      "GetDefaultEndPoint",
      [this](const Json &json, WebSocketHandler::Connection *conn) {
        Json response;
        response["type"] = "DefaultEndPoint";

206 207
        Json poi_list = Json::array();
        if (LoadPOI()) {
S
siyangy 已提交
208
          for (const auto &landmark : poi_.landmark()) {
209 210
            Json place;
            place["name"] = landmark.name();
211 212 213 214 215 216

            Json parking_info =
                apollo::common::util::JsonUtil::ProtoToTypedJson(
                    "parkingInfo", landmark.parking_info());
            place["parkingInfo"] = parking_info["data"];

217 218 219 220 221 222 223 224
            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;
225

226 227
            poi_list.push_back(place);
          }
228
        } else {
S
siyangy 已提交
229 230 231 232 233
          sim_world_service_.PublishMonitorMessage(MonitorMessageItem::ERROR,
                                                   "Failed to load default "
                                                   "POI. Please make sure the "
                                                   "file exists at " +
                                                       EndWayPointFile());
234
        }
235
        response["poi"] = poi_list;
236 237
        websocket_->SendData(conn, response.dump());
      });
S
siyangy 已提交
238 239 240 241

  websocket_->RegisterMessageHandler(
      "Reset", [this](const Json &json, WebSocketHandler::Connection *conn) {
        sim_world_service_.SetToClear();
S
siyangy 已提交
242
        sim_control_->Reset();
S
siyangy 已提交
243
      });
S
siyangy 已提交
244 245 246

  websocket_->RegisterMessageHandler(
      "Dump", [this](const Json &json, WebSocketHandler::Connection *conn) {
247
        sim_world_service_.DumpMessages();
S
siyangy 已提交
248
      });
S
siyangy 已提交
249 250 251 252 253 254 255 256 257 258 259 260 261

  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();
          }
        }
      });
V
vlin17 已提交
262 263 264 265 266 267 268 269 270
  websocket_->RegisterMessageHandler(
      "RequestDataCollectionProgress",
      [this](const Json &json, WebSocketHandler::Connection *conn) {
        if (!data_collection_monitor_->IsEnabled()) {
          return;
        }

        Json response;
        response["type"] = "DataCollectionProgress";
V
vlin17 已提交
271
        response["data"] = data_collection_monitor_->GetProgressAsJson();
V
vlin17 已提交
272 273
        websocket_->SendData(conn, response.dump());
      });
274 275 276 277 278 279 280 281 282 283
  camera_ws_->RegisterMessageHandler(
      "RequestCameraData",
      [this](const Json &json, WebSocketHandler::Connection *conn) {
        if (!perception_camera_updater_->IsEnabled()) {
          return;
        }
        std::string to_send;
        perception_camera_updater_->GetUpdate(&to_send);
        camera_ws_->SendBinaryData(conn, to_send, true);
      });
284 285
}

286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306
Json SimulationWorldUpdater::CheckRoutingPoint(const Json &json) {
  Json result;
  if (!ContainsKey(json, "point")) {
    result["error"] = "Failed to check routing point: point not found.";
    AERROR << result["error"];
    return result;
  }
  auto point = json["point"];
  if (!ValidateCoordinate(point) || !ContainsKey(point, "id")) {
    result["error"] = "Failed to check routing point: invalid point.";
    AERROR << result["error"];
    return result;
  }
  if (!map_service_->CheckRoutingPoint(point["x"], point["y"])) {
    result["pointId"] = point["id"];
    result["error"] = "Selected point cannot be a routing point.";
    AWARN << result["error"];
  }
  return result;
}

307
bool SimulationWorldUpdater::ConstructRoutingRequest(
S
siyangy 已提交
308
    const Json &json, RoutingRequest *routing_request) {
309 310
  routing_request->clear_waypoint();
  // set start point
311
  if (!ContainsKey(json, "start")) {
312
    AERROR << "Failed to prepare a routing request: start point not found.";
313 314 315
    return false;
  }

316
  auto start = json["start"];
317 318 319 320
  if (!ValidateCoordinate(start)) {
    AERROR << "Failed to prepare a routing request: invalid start point.";
    return false;
  }
321 322 323 324 325 326 327 328 329 330 331 332 333 334 335
  if (ContainsKey(start, "heading")) {
    if (!map_service_->ConstructLaneWayPointWithHeading(
            start["x"], start["y"], start["heading"],
            routing_request->add_waypoint())) {
      AERROR << "Failed to prepare a routing request with heading: "
             << start["heading"] << " cannot locate start point on map.";
      return false;
    }
  } else {
    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.";
      return false;
    }
336 337 338 339
  }

  // set way point(s) if any
  auto iter = json.find("waypoint");
340
  if (iter != json.end() && iter->is_array()) {
S
siyangy 已提交
341
    auto *waypoint = routing_request->mutable_waypoint();
342
    for (size_t i = 0; i < iter->size(); ++i) {
S
siyangy 已提交
343
      auto &point = (*iter)[i];
344 345
      if (!ValidateCoordinate(point)) {
        AERROR << "Failed to prepare a routing request: invalid waypoint.";
S
siyangy 已提交
346 347 348
        return false;
      }

349 350
      if (!map_service_->ConstructLaneWayPoint(point["x"], point["y"],
                                               waypoint->Add())) {
351
        AERROR << "Failed to construct a LaneWayPoint, skipping.";
352 353 354 355 356 357
        waypoint->RemoveLast();
      }
    }
  }

  // set end point
358
  if (!ContainsKey(json, "end")) {
359
    AERROR << "Failed to prepare a routing request: end point not found.";
360 361
    return false;
  }
362

363
  auto end = json["end"];
364 365 366 367 368 369 370 371
  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.";
372
    return false;
373 374
  }

375 376 377 378 379 380 381 382 383
  // set parking info
  if (ContainsKey(json, "parkingInfo")) {
    auto *requested_parking_info = routing_request->mutable_parking_info();
    if (!JsonStringToMessage(json["parkingInfo"].dump(), requested_parking_info)
             .ok()) {
      AERROR << "Failed to prepare a routing request: invalid parking info."
             << json["parkingInfo"].dump();
      return false;
    }
384 385
  }

386
  AINFO << "Constructed RoutingRequest to be sent:\n"
S
siyangy 已提交
387
        << routing_request->DebugString();
388

389
  return true;
S
siyangy 已提交
390 391
}

392 393 394 395 396 397 398 399 400 401 402 403
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 已提交
404
void SimulationWorldUpdater::Start() {
G
GoLancer 已提交
405
  timer_.reset(new cyber::Timer(kSimWorldTimeIntervalMs,
406
                                [this]() { this->OnTimer(); }, false));
407
  timer_->Start();
S
siyangy 已提交
408 409
}

410
void SimulationWorldUpdater::OnTimer() {
S
siyangy 已提交
411
  sim_world_service_.Update();
412 413 414

  {
    boost::unique_lock<boost::shared_mutex> writer_lock(mutex_);
415 416
    last_pushed_adc_timestamp_sec_ =
        sim_world_service_.world().auto_driving_car().timestamp_sec();
417 418 419
    sim_world_service_.GetWireFormatString(
        FLAGS_sim_map_radius, &simulation_world_,
        &simulation_world_with_planning_data_);
S
siyangy 已提交
420 421
    sim_world_service_.GetRelativeMap().SerializeToString(
        &relative_map_string_);
422
  }
S
siyangy 已提交
423 424
}

425
bool SimulationWorldUpdater::LoadPOI() {
426
  if (GetProtoFromASCIIFile(EndWayPointFile(), &poi_)) {
427
    return true;
428
  }
429

430
  AWARN << "Failed to load default list of POI from " << EndWayPointFile();
431
  return false;
432 433
}

S
siyangy 已提交
434 435
}  // namespace dreamview
}  // namespace apollo