simulation_world_updater.cc 14.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 42 43
SimulationWorldUpdater::SimulationWorldUpdater(
    WebSocketHandler *websocket, WebSocketHandler *map_ws,
    SimControl *sim_control, const MapService *map_service,
    DataCollectionMonitor *data_collection_monitor, bool routing_from_file)
S
siyangy 已提交
44
    : 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),
V
vlin17 已提交
48 49
      sim_control_(sim_control),
      data_collection_monitor_(data_collection_monitor) {
50 51 52 53
  RegisterMessageHandlers();
}

void SimulationWorldUpdater::RegisterMessageHandlers() {
54 55 56 57 58 59 60 61
  // 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 已提交
62

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

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

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

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

V
vlin17 已提交
93 94
  websocket_->RegisterMessageHandler(
      "Binary",
95
      [this](const std::string &data, WebSocketHandler::Connection *conn) {
S
siyangy 已提交
96
        // Navigation info in binary format
97
        auto navigation_info = std::make_shared<NavigationInfo>();
98 99
        if (navigation_info->ParseFromString(data)) {
          sim_world_service_.PublishNavigationInfo(navigation_info);
V
vlin17 已提交
100 101 102 103 104 105
        } 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 137 138 139 140 141
  websocket_->RegisterMessageHandler(
      "CheckRoutingPoint",
      [this](const Json &json, WebSocketHandler::Connection *conn) {
        Json response = CheckRoutingPoint(json);
        response["type"] = "RoutingPointCheckResult";
        websocket_->SendData(conn, response.dump());
      });

142 143 144
  websocket_->RegisterMessageHandler(
      "SendRoutingRequest",
      [this](const Json &json, WebSocketHandler::Connection *conn) {
145
        auto routing_request = std::make_shared<RoutingRequest>();
146

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

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

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

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

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

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

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

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

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

        Json response;
        response["type"] = "DataCollectionProgress";
V
vlin17 已提交
261
        response["data"] = data_collection_monitor_->GetProgressAsJson();
V
vlin17 已提交
262 263
        websocket_->SendData(conn, response.dump());
      });
264 265
}

266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286
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;
}

287
bool SimulationWorldUpdater::ConstructRoutingRequest(
S
siyangy 已提交
288
    const Json &json, RoutingRequest *routing_request) {
289 290
  routing_request->clear_waypoint();
  // set start point
291
  if (!ContainsKey(json, "start")) {
292
    AERROR << "Failed to prepare a routing request: start point not found.";
293 294 295
    return false;
  }

296
  auto start = json["start"];
297 298 299 300
  if (!ValidateCoordinate(start)) {
    AERROR << "Failed to prepare a routing request: invalid start point.";
    return false;
  }
301 302 303 304 305 306 307 308 309 310 311 312 313 314 315
  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;
    }
316 317 318 319
  }

  // set way point(s) if any
  auto iter = json.find("waypoint");
320
  if (iter != json.end() && iter->is_array()) {
S
siyangy 已提交
321
    auto *waypoint = routing_request->mutable_waypoint();
322
    for (size_t i = 0; i < iter->size(); ++i) {
S
siyangy 已提交
323
      auto &point = (*iter)[i];
324 325
      if (!ValidateCoordinate(point)) {
        AERROR << "Failed to prepare a routing request: invalid waypoint.";
S
siyangy 已提交
326 327 328
        return false;
      }

329 330
      if (!map_service_->ConstructLaneWayPoint(point["x"], point["y"],
                                               waypoint->Add())) {
331
        AERROR << "Failed to construct a LaneWayPoint, skipping.";
332 333 334 335 336 337
        waypoint->RemoveLast();
      }
    }
  }

  // set end point
338
  if (!ContainsKey(json, "end")) {
339
    AERROR << "Failed to prepare a routing request: end point not found.";
340 341
    return false;
  }
342

343
  auto end = json["end"];
344 345 346 347 348 349 350 351
  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.";
352
    return false;
353 354
  }

355
  // set parking space
V
vlin17 已提交
356 357
  if (ContainsKey(json, "parkingSpaceId") &&
      json.find("parkingSpaceId")->is_string()) {
358 359 360 361
    routing_request->mutable_parking_space()->mutable_id()->set_id(
        json["parkingSpaceId"]);
  }

362
  AINFO << "Constructed RoutingRequest to be sent:\n"
S
siyangy 已提交
363
        << routing_request->DebugString();
364

365
  return true;
S
siyangy 已提交
366 367
}

368 369 370 371 372 373 374 375 376 377 378 379
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 已提交
380
void SimulationWorldUpdater::Start() {
G
GoLancer 已提交
381
  timer_.reset(new cyber::Timer(kSimWorldTimeIntervalMs,
382
                                [this]() { this->OnTimer(); }, false));
383
  timer_->Start();
S
siyangy 已提交
384 385
}

386
void SimulationWorldUpdater::OnTimer() {
S
siyangy 已提交
387
  sim_world_service_.Update();
388 389 390

  {
    boost::unique_lock<boost::shared_mutex> writer_lock(mutex_);
391 392 393
    sim_world_service_.GetWireFormatString(
        FLAGS_sim_map_radius, &simulation_world_,
        &simulation_world_with_planning_data_);
S
siyangy 已提交
394 395
    sim_world_service_.GetRelativeMap().SerializeToString(
        &relative_map_string_);
396
  }
S
siyangy 已提交
397 398
}

399
bool SimulationWorldUpdater::LoadPOI() {
400
  if (GetProtoFromASCIIFile(EndWayPointFile(), &poi_)) {
401
    return true;
402
  }
403

404
  AWARN << "Failed to load default list of POI from " << EndWayPointFile();
405
  return false;
406 407
}

S
siyangy 已提交
408 409
}  // namespace dreamview
}  // namespace apollo