simulation_world_updater.cc 14.8 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
            place["parkingSpaceId"] = landmark.parking_space_id();
212 213 214 215 216 217 218 219
            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;
220 221
            poi_list.push_back(place);
          }
222
        } else {
S
siyangy 已提交
223 224 225 226 227
          sim_world_service_.PublishMonitorMessage(MonitorMessageItem::ERROR,
                                                   "Failed to load default "
                                                   "POI. Please make sure the "
                                                   "file exists at " +
                                                       EndWayPointFile());
228
        }
229
        response["poi"] = poi_list;
230 231
        websocket_->SendData(conn, response.dump());
      });
S
siyangy 已提交
232 233 234 235

  websocket_->RegisterMessageHandler(
      "Reset", [this](const Json &json, WebSocketHandler::Connection *conn) {
        sim_world_service_.SetToClear();
S
siyangy 已提交
236
        sim_control_->Reset();
S
siyangy 已提交
237
      });
S
siyangy 已提交
238 239 240

  websocket_->RegisterMessageHandler(
      "Dump", [this](const Json &json, WebSocketHandler::Connection *conn) {
241
        sim_world_service_.DumpMessages();
S
siyangy 已提交
242
      });
S
siyangy 已提交
243 244 245 246 247 248 249 250 251 252 253 254 255

  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 已提交
256 257 258 259 260 261 262 263 264
  websocket_->RegisterMessageHandler(
      "RequestDataCollectionProgress",
      [this](const Json &json, WebSocketHandler::Connection *conn) {
        if (!data_collection_monitor_->IsEnabled()) {
          return;
        }

        Json response;
        response["type"] = "DataCollectionProgress";
V
vlin17 已提交
265
        response["data"] = data_collection_monitor_->GetProgressAsJson();
V
vlin17 已提交
266 267
        websocket_->SendData(conn, response.dump());
      });
268 269 270 271 272 273 274 275 276 277
  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);
      });
278 279
}

280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300
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;
}

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

310
  auto start = json["start"];
311 312 313 314
  if (!ValidateCoordinate(start)) {
    AERROR << "Failed to prepare a routing request: invalid start point.";
    return false;
  }
315 316 317 318 319 320 321 322 323 324 325 326 327 328 329
  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;
    }
330 331 332 333
  }

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

343 344
      if (!map_service_->ConstructLaneWayPoint(point["x"], point["y"],
                                               waypoint->Add())) {
345
        AERROR << "Failed to construct a LaneWayPoint, skipping.";
346 347 348 349 350 351
        waypoint->RemoveLast();
      }
    }
  }

  // set end point
352
  if (!ContainsKey(json, "end")) {
353
    AERROR << "Failed to prepare a routing request: end point not found.";
354 355
    return false;
  }
356

357
  auto end = json["end"];
358 359 360 361 362 363 364 365
  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.";
366
    return false;
367 368
  }

369
  // set parking space
V
vlin17 已提交
370 371
  if (ContainsKey(json, "parkingSpaceId") &&
      json.find("parkingSpaceId")->is_string()) {
372 373 374 375
    routing_request->mutable_parking_space()->mutable_id()->set_id(
        json["parkingSpaceId"]);
  }

376
  AINFO << "Constructed RoutingRequest to be sent:\n"
S
siyangy 已提交
377
        << routing_request->DebugString();
378

379
  return true;
S
siyangy 已提交
380 381
}

382 383 384 385 386 387 388 389 390 391 392 393
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 已提交
394
void SimulationWorldUpdater::Start() {
G
GoLancer 已提交
395
  timer_.reset(new cyber::Timer(kSimWorldTimeIntervalMs,
396
                                [this]() { this->OnTimer(); }, false));
397
  timer_->Start();
S
siyangy 已提交
398 399
}

400
void SimulationWorldUpdater::OnTimer() {
S
siyangy 已提交
401
  sim_world_service_.Update();
402 403 404

  {
    boost::unique_lock<boost::shared_mutex> writer_lock(mutex_);
405 406 407
    sim_world_service_.GetWireFormatString(
        FLAGS_sim_map_radius, &simulation_world_,
        &simulation_world_with_planning_data_);
S
siyangy 已提交
408 409
    sim_world_service_.GetRelativeMap().SerializeToString(
        &relative_map_string_);
410
  }
S
siyangy 已提交
411 412
}

413
bool SimulationWorldUpdater::LoadPOI() {
414
  if (GetProtoFromASCIIFile(EndWayPointFile(), &poi_)) {
415
    return true;
416
  }
417

418
  AWARN << "Failed to load default list of POI from " << EndWayPointFile();
419
  return false;
420 421
}

S
siyangy 已提交
422 423
}  // namespace dreamview
}  // namespace apollo