為已排定的工作建立運送車輛

本文說明如何使用 gRPC 或 REST 從伺服器環境建立車輛。只要您使用適當的憑證,將應用程式佈建為可信任的環境,即可透過 Driver SDK 建立車輛。

如要瞭解如何使用 Driver SDK 建立車輛,請參閱以下內容:

  • 用於排定工作時間的 Driver SDK
  • Fleet Engine 基本資訊下方的「服務帳戶角色」

如要從伺服器環境建立新車輛,請向 Fleet Engine 提出 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}"

後續步驟