Interact with the driver

Software on Fuchsia interacts with driver components through their exposed service capabilities. Once a client connects to the driver's service, it receives an instance of the FIDL protocol representing that driver. For more details, see the Driver Communication guide.

In this section, you'll create a new eductl executable that discovers and interacts with the capabilities exposed by the qemu_edu driver.

Create a new tools component

Create a new project directory in your Bazel workspace for a new binary tool:

mkdir -p fuchsia-codelab/qemu_edu/tools

After you complete this section, the project should have the following directory structure:

//fuchsia-codelab/qemu_edu/tools
                  |- BUILD.bazel
                  |- eductl.cc

Create the qemu_edu/tools/BUILD.bazel file and add the following statement to include the necessary build rules from the Fuchsia SDK:

qemu_edu/tools/BUILD.bazel:

load(
    "@rules_fuchsia//fuchsia:defs.bzl",
    "fuchsia_cc_binary",
    "fuchsia_component",
    "fuchsia_component_manifest",
    "fuchsia_driver_tool",
    "fuchsia_package",
)

Create a new qemu_edu/tools/eductl.cc file with the following code to set up a basic command line executable:

qemu_edu/tools/eductl.cc:

#include <ctype.h>
#include <dirent.h>
#include <fcntl.h>
#include <getopt.h>
#include <lib/component/incoming/cpp/service_member_watcher.h>
#include <libgen.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>

#include <filesystem>

int usage(const char* cmd) {
  fprintf(stderr,
          "\nInteract with the QEMU edu device:\n"
          "   %s live                       Performs a card liveness check\n"
          "   %s fact <n>                   Computes the factorial of n\n"
          "   %s help                       Print this message\n",
          cmd, cmd, cmd);
  return -1;
}

// Returns "true" if the argument matches the prefix.
// In this case, moves the argument past the prefix.
bool prefix_match(const char** arg, const char* prefix) {
  if (!strncmp(*arg, prefix, strlen(prefix))) {
    *arg += strlen(prefix);
    return true;
  }
  return false;
}

constexpr long kBadParse = -1;
long parse_positive_long(const char* number) {
  char* end;
  long result = strtol(number, &end, 10);
  if (end == number || *end != '\0' || result < 0) {
    return kBadParse;
  }
  return result;
}

int main(int argc, char* argv[]) {
  const char* cmd = basename(argv[0]);

  // ...

  return usage(cmd);
}

This executable supports two subcommands to execute the liveness check and factorial computation.

Add the following new rules to the bottom of the project's build configuration to build this new tool into a Fuchsia package:

qemu_edu/tools/BUILD.bazel:

fuchsia_cc_binary(
    name = "eductl",
    srcs = [
        "eductl.cc",
    ],
    deps = [
        "@fuchsia_sdk//pkg/component_incoming_cpp",
        "@fuchsia_sdk//pkg/fdio",
        "@fuchsia_sdk//pkg/fidl_cpp_wire",
    ],
)

fuchsia_driver_tool(
    name = "eductl_tool",
    binary = ":eductl",
    visibility = ["//visibility:public"],
)

fuchsia_package(
    name = "pkg",
    package_name = "eductl",
    tools = [
        ":eductl_tool",
    ],
    visibility = ["//visibility:public"],
)

Implement the client tool

Clients connect to the driver's exposed service to receive an instance of the FIDL protocol. Add the following code to eductl to connect to the edu device service:

qemu_edu/tools/eductl.cc:

#include <ctype.h>
#include <dirent.h>
#include <fcntl.h>
#include <getopt.h>
#include <lib/component/incoming/cpp/service_member_watcher.h>
#include <libgen.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>

#include <filesystem>

#include <fidl/examples.qemuedu/cpp/wire.h>

// Open a FIDL client connection to the examples.qemuedu.Device
zx::result<fidl::WireSyncClient<examples_qemuedu::Device>> ConnectToDevice() {
  component::SyncServiceMemberWatcher<examples_qemuedu::Service::Device> watcher;
  zx::result<fidl::ClientEnd<examples_qemuedu::Device>> client_end = watcher.GetNextInstance(true);
  if (client_end.is_error()) {
    fprintf(stderr, "Failed to connect to device service: %s\n", client_end.status_string());
    return client_end.take_error();
  }
  return zx::ok(fidl::WireSyncClient(std::move(*client_end)));
}

// ...

Add liveness_check() and compute_factorial() functions to call methods using the examples.qemuedu/Device FIDL protocol returned from ConnectToDevice(). Finally, update the tool's main() function to call the appropriate device function based on the argument passed on the command line:

qemu_edu/tools/eductl.cc:

// ...

// Run a liveness check on the QEMU edu device.
// Returns 0 on success.
int liveness_check() {
  auto client_result = ConnectToDevice();
  if (client_result.is_error()) {
    return -1;
  }
  auto& client = client_result.value();

  auto liveness_check_result = client->LivenessCheck();
  if (!liveness_check_result.ok()) {
    fprintf(stderr, "Error: failed to get liveness check result: %s\n",
            zx_status_get_string(liveness_check_result.status()));
    return -1;
  }

  if (liveness_check_result->value()->result) {
    printf("Liveness check passed!\n");
    return 0;
  } else {
    printf("Liveness check failed!\n");
    return -1;
  }
}

// Compute the factorial of n using the QEMU edu device.
// Returns 0 on success.
int compute_factorial(long n) {
  auto client_result = ConnectToDevice();
  if (client_result.is_error()) {
    return -1;
  }
  auto& client = client_result.value();

  if (n >= std::numeric_limits<uint32_t>::max()) {
    fprintf(stderr, "N is too large\n");
    return -1;
  }

  uint32_t input = static_cast<uint32_t>(n);
  auto compute_factorial_result = client->ComputeFactorial(input);
  if (!compute_factorial_result.ok()) {
    fprintf(stderr, "Error: failed to call compute factorial result: %s\n",
            zx_status_get_string(compute_factorial_result.status()));
    return -1;
  }

  printf("Factorial(%u) = %u\n", input, compute_factorial_result->value()->output);

  return 0;
}

int main(int argc, char* argv[]) {
  const char* cmd = basename(argv[0]);

  // If no arguments passed, bail out after dumping
  // usage information.
  if (argc < 2) {
    return usage(cmd);
  }

  const char* arg = argv[1];
  if (prefix_match(&arg, "live")) {
    return liveness_check();
  } else if (prefix_match(&arg, "fact")) {
    if (argc < 3) {
      fprintf(stderr, "Expecting 1 argument\n");
      return usage(cmd);
    }
    long n = parse_positive_long(argv[2]);
    return compute_factorial(n);
  }

  return usage(cmd);
}

Update the tool's build configuration to depend on the FIDL bindings for the examples.qemuedu library:

qemu_edu/tools/BUILD.bazel:

fuchsia_cc_binary(
    name = "eductl",
    srcs = [
        "eductl.cc",
    ],
    deps = [
        "//fuchsia-codelab/qemu_edu/fidl:examples.qemuedu_cc",
        "@fuchsia_sdk//pkg/component_incoming_cpp",
        "@fuchsia_sdk//pkg/fdio",
        "@fuchsia_sdk//pkg/fidl_cpp_wire",
    ],
)

Restart the emulator

Shut down any existing emulator instances:

ffx emu stop --all

Start a new instance of the Fuchsia emulator with driver framework enabled:

ffx emu start core.x64 --headless

Reload the driver

Use the bazel run command to build and execute the driver component target:

bazel run //fuchsia-codelab/qemu_edu/drivers:pkg.component

Run the tool

Use the bazel run command to build and execute the tool, passing the arguments fact 12 to compute the factorial of 12:

bazel run //fuchsia-codelab/qemu_edu/tools:pkg.eductl_tool -- fact 12

The bazel run command performs the following steps:

  1. Build the executable and package.
  2. Publish the package to a local package repository.
  3. Register the package repository with the target device.
  4. Use ffx driver run-tool to run the binary inside the driver_playground component.

The command prints output similar to the following with the computation result the factorial:

Factorial(12) = 479001600

Congratulations! You've successfully connected to your driver's exposed services from a separate client.