simulation_world_updater.cc 12.9 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 {

28
using apollo::common::monitor::MonitorMessageItem;
29
using apollo::common::util::ContainsKey;
30 31
using apollo::common::util::GetProtoFromASCIIFile;
using apollo::common::util::JsonUtil;
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

40
SimulationWorldUpdater::SimulationWorldUpdater(WebSocketHandler *websocket,
41
                                               WebSocketHandler *map_ws,
S
siyangy 已提交
42
                                               SimControl *sim_control,
43
                                               const MapService *map_service,
S
siyangy 已提交
44 45
                                               bool routing_from_file)
    : sim_world_service_(map_service, routing_from_file),
46
      map_service_(map_service),
S
siyangy 已提交
47
      websocket_(websocket),
S
siyangy 已提交
48
      map_ws_(map_ws),
S
siyangy 已提交
49
      sim_control_(sim_control) {
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
  websocket_->RegisterMessageHandler(
      "SendRoutingRequest",
      [this](const Json &json, WebSocketHandler::Connection *conn) {
137
        auto routing_request = std::make_shared<RoutingRequest>();
138

139
        bool succeed = ConstructRoutingRequest(json, routing_request.get());
140
        if (succeed) {
141
          sim_world_service_.PublishRoutingRequest(routing_request);
142
          sim_world_service_.PublishMonitorMessage(MonitorMessageItem::INFO,
V
vlin17 已提交
143
                                                   "Routing request sent.");
144
        } else {
S
siyangy 已提交
145
          sim_world_service_.PublishMonitorMessage(
V
vlin17 已提交
146
              MonitorMessageItem::ERROR, "Failed to send a routing request.");
147
        }
148
      });
149 150

  websocket_->RegisterMessageHandler(
151 152
      "RequestSimulationWorld",
      [this](const Json &json, WebSocketHandler::Connection *conn) {
153 154 155 156 157 158
        if (!sim_world_service_.ReadyToPush()) {
          AWARN_EVERY(100)
              << "Not sending simulation world as the data is not ready!";
          return;
        }

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

S
siyangy 已提交
180 181 182 183 184 185 186 187
  websocket_->RegisterMessageHandler(
      "RequestRoutePath",
      [this](const Json &json, WebSocketHandler::Connection *conn) {
        Json response = sim_world_service_.GetRoutePathAsJson();
        response["type"] = "RoutePath";
        websocket_->SendData(conn, response.dump());
      });

188 189 190 191 192 193
  websocket_->RegisterMessageHandler(
      "GetDefaultEndPoint",
      [this](const Json &json, WebSocketHandler::Connection *conn) {
        Json response;
        response["type"] = "DefaultEndPoint";

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

  websocket_->RegisterMessageHandler(
      "Reset", [this](const Json &json, WebSocketHandler::Connection *conn) {
        sim_world_service_.SetToClear();
S
siyangy 已提交
224
        sim_control_->Reset();
S
siyangy 已提交
225
      });
S
siyangy 已提交
226 227 228

  websocket_->RegisterMessageHandler(
      "Dump", [this](const Json &json, WebSocketHandler::Connection *conn) {
229
        sim_world_service_.DumpMessages();
S
siyangy 已提交
230
      });
S
siyangy 已提交
231 232 233 234 235 236 237 238 239 240 241 242 243

  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();
          }
        }
      });
244 245 246
}

bool SimulationWorldUpdater::ConstructRoutingRequest(
S
siyangy 已提交
247
    const Json &json, RoutingRequest *routing_request) {
248 249
  routing_request->clear_waypoint();
  // set start point
250
  if (!ContainsKey(json, "start")) {
251
    AERROR << "Failed to prepare a routing request: start point not found.";
252 253 254
    return false;
  }

255
  auto start = json["start"];
256 257 258 259
  if (!ValidateCoordinate(start)) {
    AERROR << "Failed to prepare a routing request: invalid start point.";
    return false;
  }
260 261 262 263 264 265 266 267 268 269 270 271 272 273 274
  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;
    }
275 276 277 278
  }

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

288 289
      if (!map_service_->ConstructLaneWayPoint(point["x"], point["y"],
                                               waypoint->Add())) {
290
        AERROR << "Failed to construct a LaneWayPoint, skipping.";
291 292 293 294 295 296
        waypoint->RemoveLast();
      }
    }
  }

  // set end point
297
  if (!ContainsKey(json, "end")) {
298
    AERROR << "Failed to prepare a routing request: end point not found.";
299 300
    return false;
  }
301

302
  auto end = json["end"];
303 304 305 306 307 308 309 310
  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.";
311
    return false;
312 313
  }

314
  // set parking space
V
vlin17 已提交
315 316
  if (ContainsKey(json, "parkingSpaceId") &&
      json.find("parkingSpaceId")->is_string()) {
317 318 319 320
    routing_request->mutable_parking_space()->mutable_id()->set_id(
        json["parkingSpaceId"]);
  }

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

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

327 328 329 330 331 332 333 334 335 336 337 338
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 已提交
339
void SimulationWorldUpdater::Start() {
G
GoLancer 已提交
340
  timer_.reset(new cyber::Timer(kSimWorldTimeIntervalMs,
341
                                [this]() { this->OnTimer(); }, false));
342
  timer_->Start();
S
siyangy 已提交
343 344
}

345
void SimulationWorldUpdater::OnTimer() {
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