为预定任务创建交付车辆

本文档介绍了如何使用 gRPC 或 REST 从服务器环境创建车辆。您可以通过 Driver SDK 创建车辆,前提是您已使用适当的凭据将应用预配为可信环境。

如需了解如何使用 Driver SDK 创建车辆,请参阅以下内容:

如需从服务器环境创建新车辆,请向车队引擎发出 CreateDeliveryVehicle 请求。使用 CreateDeliveryVehicleRequest 对象定义新配送车辆的属性。

用于安排任务车辆的字段

创建 DeliveryVehicle 时,您可以设置以下选填字段:

  • attributes
  • last_location
  • type

如需在不设置任何可选字段的情况下创建车辆,您可以在 CreateDeliveryVehicleRequest 中将 DeliveryVehicle 字段保持未设置状态。

创建车辆示例

您可以使用 Java gRPC 库创建车辆,也可以使用 REST。

Java

  static final String PROJECT_ID = "my-delivery-co-gcp-project";
  static final String VEHICLE_ID = "vehicle-8241890"; // Avoid auto-incrementing IDs.

  DeliveryServiceBlockingStub deliveryService =
    DeliveryServiceGrpc.newBlockingStub(channel);

  // Vehicle settings
  String parent = "providers/" + PROJECT_ID;
  DeliveryVehicle vehicle = DeliveryVehicle.newBuilder()
    .addAttributes(DeliveryVehicleAttribute.newBuilder()
      .setKey("route_number").setValue("1"))  // Opaque to the Fleet Engine
    .build();

  // Vehicle request
  CreateDeliveryVehicleRequest createVehicleRequest =
    CreateDeliveryVehicleRequest.newBuilder()  // No need for the header
        .setParent(parent)
        .setDeliveryVehicleId(VEHICLE_ID)     // Vehicle ID assigned by the Provider
        .setDeliveryVehicle(vehicle)
        .build();

  // Error handling
  // If Fleet Engine does not have vehicle with that ID and the credentials of the
  // requestor pass, the service creates the vehicle successfully.

  try {
    DeliveryVehicle createdVehicle =
      deliveryService.createDeliveryVehicle(createVehicleRequest);
  } catch (StatusRuntimeException e) {
    Status s = e.getStatus();
    switch (s.getCode()) {
       case ALREADY_EXISTS:
         break;
       case PERMISSION_DENIED:
         break;
    }
    return;
  }

REST

如需从服务器环境创建车辆,请向 CreateDeliveryVehicle 发出 HTTP REST 调用:

POST https://fleetengine.googleapis.com/v1/providers/<project_id>/deliveryVehicles?deliveryVehicleId=<id>

POST 正文代表要创建的 DeliveryVehicle 实体。您可以指定以下可选字段:

  • attributes
  • lastLocation
  • type
  # Set $JWT, $PROJECT_ID, and $VEHICLE_ID in the local
  # environment
  curl -X POST "https://fleetengine.googleapis.com/v1/providers/${PROJECT_ID}/deliveryVehicles?deliveryVehicleId=${VEHICLE_ID}" \
    -H "Content-type: application/json" \
    -H "Authorization: Bearer ${JWT}" \
  --data-binary @- << EOM
  {
    "attributes": [{"key": "model", "value": "sedan"}],
    "lastLocation": {"location": {"latitude": 12.1, "longitude": 14.5}}
  }
  EOM

如需在不设置任何字段的情况下创建车辆,请将 POST 请求正文留空。然后,新创建的车辆会从 POST 网址中的 deliveryVehicleId 参数中提取车辆 ID。

示例:

  # Set $JWT, $PROJECT_ID, and $VEHICLE_ID in the local
  # environment
  curl -X POST "https://fleetengine.googleapis.com/v1/providers/${PROJECT_ID}/deliveryVehicles?deliveryVehicleId=${VEHICLE_ID}" \
    -H "Content-type: application/json" \
    -H "Authorization: Bearer ${JWT}"

后续步骤