simulation_world_updater.cc 11.0 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,
S
siyangy 已提交
40
                                               SimControl *sim_control,
41
                                               const MapService *map_service,
S
siyangy 已提交
42 43
                                               bool routing_from_file)
    : sim_world_service_(map_service, routing_from_file),
44
      map_service_(map_service),
S
siyangy 已提交
45 46
      websocket_(websocket),
      sim_control_(sim_control) {
47 48 49 50
  RegisterMessageHandlers();
}

void SimulationWorldUpdater::RegisterMessageHandlers() {
S
siyangy 已提交
51 52 53 54 55
  websocket_->RegisterMessageHandler(
      "RetrieveMapData",
      [this](const Json &json, WebSocketHandler::Connection *conn) {
        auto iter = json.find("elements");
        if (iter != json.end()) {
S
siyangy 已提交
56 57 58 59 60 61 62 63
          MapElementIds map_element_ids;
          if (JsonStringToMessage(iter->dump(), &map_element_ids).ok()) {
            auto retrieved = map_service_->RetrieveMapElements(map_element_ids);
            websocket_->SendData(
                conn, JsonUtil::ProtoToTypedJson("MapData", retrieved).dump());
          } else {
            AERROR << "Failed to parse MapElementIds from json";
          }
S
siyangy 已提交
64 65
        }
      });
66

67
  websocket_->RegisterMessageHandler(
S
siyangy 已提交
68
      "RetrieveMapElementIdsByRadius",
69 70 71
      [this](const Json &json, WebSocketHandler::Connection *conn) {
        auto radius = json.find("radius");
        if (radius == json.end()) {
72
          AERROR << "Cannot retrieve map elements with unknown radius.";
73
          return;
74 75
        }

76 77 78 79 80 81
        if (!radius->is_number()) {
          AERROR << "Expect radius with type 'number', but was "
                 << radius->type_name();
          return;
        }

S
siyangy 已提交
82 83 84 85 86 87 88 89 90 91
        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);

92
        websocket_->SendData(conn, response.dump());
93 94
      });

95 96 97
  websocket_->RegisterMessageHandler(
      "SendRoutingRequest",
      [this](const Json &json, WebSocketHandler::Connection *conn) {
98
        RoutingRequest routing_request;
99

100 101 102 103 104 105 106
        bool succeed = ConstructRoutingRequest(json, &routing_request);
        if (succeed) {
          AdapterManager::FillRoutingRequestHeader(FLAGS_dreamview_module_name,
                                                   &routing_request);
          AdapterManager::PublishRoutingRequest(routing_request);
        }

107
        // Publish monitor message.
108
        if (succeed) {
109
          sim_world_service_.PublishMonitorMessage(MonitorMessageItem::INFO,
A
Aaron Xiao 已提交
110
                                                   "Routing request Sent");
111
        } else {
S
siyangy 已提交
112 113
          sim_world_service_.PublishMonitorMessage(
              MonitorMessageItem::ERROR, "Failed to send routing request");
114
        }
115
      });
116 117

  websocket_->RegisterMessageHandler(
118 119
      "RequestSimulationWorld",
      [this](const Json &json, WebSocketHandler::Connection *conn) {
120 121 122 123 124 125
        if (!sim_world_service_.ReadyToPush()) {
          AWARN_EVERY(100)
              << "Not sending simulation world as the data is not ready!";
          return;
        }

126
        bool enable_pnc_monitor = false;
127 128
        auto planning = json.find("planning");
        if (planning != json.end() && planning->is_boolean()) {
129
          enable_pnc_monitor = json["planning"];
130
        }
131 132 133 134 135
        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_);
136 137
          to_send = enable_pnc_monitor ? simulation_world_with_planning_data_
                                       : simulation_world_;
138
        }
139
        if (FLAGS_enable_update_size_check && !enable_pnc_monitor &&
140 141 142 143
            to_send.size() > FLAGS_max_update_size) {
          AWARN << "update size is too big:" << to_send.size();
          return;
        }
S
siyangy 已提交
144
        websocket_->SendBinaryData(conn, to_send, true);
145
      });
146 147 148 149 150 151 152

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

153 154
        Json poi_list = Json::array();
        if (LoadPOI()) {
S
siyangy 已提交
155
          for (const auto &landmark : poi_.landmark()) {
156 157
            Json place;
            place["name"] = landmark.name();
158 159 160 161 162 163 164 165
            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;
166 167
            poi_list.push_back(place);
          }
168
        } else {
S
siyangy 已提交
169 170 171 172 173
          sim_world_service_.PublishMonitorMessage(MonitorMessageItem::ERROR,
                                                   "Failed to load default "
                                                   "POI. Please make sure the "
                                                   "file exists at " +
                                                       EndWayPointFile());
174
        }
175
        response["poi"] = poi_list;
176 177
        websocket_->SendData(conn, response.dump());
      });
S
siyangy 已提交
178 179 180 181

  websocket_->RegisterMessageHandler(
      "Reset", [this](const Json &json, WebSocketHandler::Connection *conn) {
        sim_world_service_.SetToClear();
S
siyangy 已提交
182
        sim_control_->Reset();
S
siyangy 已提交
183
      });
S
siyangy 已提交
184 185 186 187 188 189 190 191 192

  websocket_->RegisterMessageHandler(
      "Dump", [this](const Json &json, WebSocketHandler::Connection *conn) {
        DumpMessage(AdapterManager::GetChassis(), "Chassis");
        DumpMessage(AdapterManager::GetPrediction(), "Prediction");
        DumpMessage(AdapterManager::GetRoutingResponse(), "RoutingResponse");
        DumpMessage(AdapterManager::GetLocalization(), "Localization");
        DumpMessage(AdapterManager::GetPlanning(), "Planning");
      });
S
siyangy 已提交
193 194 195 196 197 198 199 200 201 202 203 204 205

  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();
          }
        }
      });
206 207 208
}

bool SimulationWorldUpdater::ConstructRoutingRequest(
S
siyangy 已提交
209
    const Json &json, RoutingRequest *routing_request) {
210 211
  routing_request->clear_waypoint();
  // set start point
212
  if (!ContainsKey(json, "start")) {
213
    AERROR << "Failed to prepare a routing request: start point not found.";
214 215 216
    return false;
  }

217
  auto start = json["start"];
218 219 220 221 222 223 224 225
  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.";
226 227 228 229 230
    return false;
  }

  // set way point(s) if any
  auto iter = json.find("waypoint");
231
  if (iter != json.end() && iter->is_array()) {
S
siyangy 已提交
232
    auto *waypoint = routing_request->mutable_waypoint();
233
    for (size_t i = 0; i < iter->size(); ++i) {
S
siyangy 已提交
234
      auto &point = (*iter)[i];
235 236
      if (!ValidateCoordinate(point)) {
        AERROR << "Failed to prepare a routing request: invalid waypoint.";
S
siyangy 已提交
237 238 239
        return false;
      }

240 241 242 243 244 245 246 247
      if (!map_service_->ConstructLaneWayPoint(point["x"], point["y"],
                                               waypoint->Add())) {
        waypoint->RemoveLast();
      }
    }
  }

  // set end point
248
  if (!ContainsKey(json, "end")) {
249
    AERROR << "Failed to prepare a routing request: end point not found.";
250 251
    return false;
  }
252

253
  auto end = json["end"];
254 255 256 257 258 259 260 261
  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.";
262
    return false;
263 264
  }

265
  AINFO << "Constructed RoutingRequest to be sent:\n"
S
siyangy 已提交
266
        << routing_request->DebugString();
267

268
  return true;
S
siyangy 已提交
269 270
}

271 272 273 274 275 276 277 278 279 280 281 282
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 已提交
283 284
void SimulationWorldUpdater::Start() {
  // start ROS timer, one-shot = false, auto-start = true
S
siyangy 已提交
285 286 287
  timer_ =
      AdapterManager::CreateTimer(ros::Duration(kSimWorldTimeIntervalMs / 1000),
                                  &SimulationWorldUpdater::OnTimer, this);
S
siyangy 已提交
288 289
}

290
void SimulationWorldUpdater::OnTimer(const ros::TimerEvent &event) {
S
siyangy 已提交
291
  sim_world_service_.Update();
292 293 294

  {
    boost::unique_lock<boost::shared_mutex> writer_lock(mutex_);
295 296 297
    sim_world_service_.GetWireFormatString(
        FLAGS_sim_map_radius, &simulation_world_,
        &simulation_world_with_planning_data_);
298
  }
S
siyangy 已提交
299 300
}

301
bool SimulationWorldUpdater::LoadPOI() {
302
  if (GetProtoFromASCIIFile(EndWayPointFile(), &poi_)) {
303
    return true;
304
  }
305

306
  AWARN << "Failed to load default list of POI from " << EndWayPointFile();
307
  return false;
308 309
}

S
siyangy 已提交
310 311
}  // namespace dreamview
}  // namespace apollo