# Provision devices using API

## Overview

The Guardian API provides full lifecycle device provisioning, as well as secure communication and cryptographic operations for medical devices. By integrating the [Guardian Library](https://docs.medcrypt.com/overview/what-is-guardian#guardian-components) directly into your application code, you gain programmatic control over the entire provisioning process without the need for manual intervention or external tools.

This topic focuses on the three main provisioning workflows you can accomplish with the API:&#x20;

* [Disconnected devices](#disconnected-device-provisioning)
* [Connected devices](#connected-device-provisioning)
* [Proxy provisioning](#proxy-device-provisioning)&#x20;

Refer to [Terminology](https://docs.medcrypt.com/get-started/terminology) for more information on process, platform, provisioning and other terms.

### When to use the API

* You need to embed provisioning logic directly in your device software
* You need automated provisioning workflows without manual intervention
* You need fine-grained control over the provisioning process
* You need to integrate with existing device management systems

## General prerequisites

Before beginning device provisioning, ensure you have:

* Guardian account
* Created and configured your system in Guardian
* Received your provisioning package from Medcrypt
* Downloaded and installed Guardian Library for your platform&#x20;
* Installed provisioning package on your device&#x20;

## **Disconnected device provisioning**

**When to use:** For devices without network connectivity where provisioning requests must be manually transferred to Guardian Cloud. or more details on file types and extensions, refer to [Guardian file types](https://docs.medcrypt.com/manage-devices/begin-device-provisioning/..#guardian-file-types-and-extensions).

1. **Prepare provisioning files:** Load the content of the provisioning files into your application's memory. This includes the following files:

   1. TrustStore (`.mcts`)
   2. Private identity for provisioning (`.mcpip`)
   3. Certified profile for provisioning (`.mcpp`)&#x20;

   Your application refers to the software you are developing that integrates the Guardian Library.&#x20;
2. **Create a new Guardian instance:** This action initializes member variables and puts the system in a startup state.
3. **Generate provision request and private identity files:** Call the [GenerateProvisionRequest()](#step-3-generate-provisioning-request)  function. This is the first provisioning step and the only one in the offline process. It generates device keys and creates a provision request (`.mcpr`) file and a private identity (`.mcpi`) file. The `.mcpi` file contains the private keys that stay on the device.
4. Save the generated provision request and private identity files to local storage.
5. **Upload PR:** Manually upload the provision request file to Guardian Cloud.&#x20;
6. **Download certified profile**: Once the PR is processed and approved, download the `.mcp` file from the Guardian Cloud UI.
7. **Install certified profile on device**: Transfer the `.mcp` file to the device where the `.mcpi` file is located to complete provisioning.

## **Connected device provisioning**

**When to use:** For devices with network connectivity that can communicate directly with Guardian Cloud. It is a fully automated process with no manual intervention required. For more details on file types and extensions, refer to [Guardian file types](https://docs.medcrypt.com/manage-devices/begin-device-provisioning/..#guardian-file-types-and-extensions).

1. Follow steps 1-3 in [Disconnected provisioning](#disconnected-device-provisioning) above to load your provisioning files, start Guardian, and generate the PR and private identity files.
2. **Submit PR to Guardian Cloud:** Call [StartProvisioningOnline()](https://docs.medcrypt.com/api-reference/api-overview#startprovisioningonline) to automatically submit the provisioning request. This initiates the online provisioning state machine and begins communication with Guardian Cloud.
3. **Monitor provisioning progress:**&#x20;
   1. Call the Run function repeatedly within your application's main loop to exectuve background tasks.&#x20;
   2. Use [IsProvisioningRunning()](#isprovisioningrunning) to check if the process is still active.
4. **Retrieve and save certified profile:**&#x20;
   1. When [IsProvisioningRunning()](#isprovisioningrunning) is `false`, the process is finished.&#x20;
   2. Call [GetProvisionedProfile()](#getprovisionedprofile) to retrieve the completed Certified Profile.&#x20;
5. Persist or save this file to your device's storage.

## Proxy device provisioning

**When to use:** Using a connected device (the proxy) to handle provisioning requests for other disconnected devices.&#x20;

**Setup requirements**

* The **proxy device must be provisioned as a fully online component** before it can upload other devices' provisioning requests.
* The disconnected device's `.mcpr` file must be transferred to the proxy device first

**Provision using proxy**

1. **Initialize the proxy device:** The proxy device must first be provisioned as a fully online component. You must initialize the Guardian instance on the proxy device with the proxy's own certified profile (`.mcp`) – this is the final profile file.
2. **Retrieve and save certified profile for other device:**&#x20;
   1. When [IsProvisioningRunning()](#isprovisioningrunning) is `false`, the process is finished.&#x20;
   2. Call [GetProvisionedProfile()](#getprovisionedprofile) to retrieve the completed certified profile.&#x20;
3. **Install certified profile on device**: Transfer the `.mcp` file to the device where the `.mcpi` file is located to complete provisioning.

## Function overview

### Device provisioning functions

* [Guardian](#step-1-run-guardian) : The constructor does no work besides initializing member variables.
* [Initialize](#step-2-run-initialize): Uses the provided profile, identity, and trust files to initialize the Guardian system.
* [GenerateProvisionRequest](#step-3-run-generateprovisionrequest): This is the first device provisioning step for the provisioning process.
* [StartProvisioningOnline](#step-4-startprovisioningonline): Start the online device provisioning process.
* [IsProvisioningRunning](https://docs.medcrypt.com/api-reference/api-reference/classes/classmedcrypt-guardian-guardian#function-isprovisioningrunning): Check if provisioning process is active.
* [GetProvisionedProfile](#getprovisionedprofile): Extract provisioned certified profile for device after successful device provisioning.

### Certificate management functions

* [GetCertificateManager:](#getcertificatemanager) Retrieve the running certificate manager.
* [GetProvisionedRevocationList](#getprovisionedrevocationlist): Retrieve certificate revocation list and populate into buffer.&#x20;

### **Security operations functions**

* [FindSecureOperation](#findsecureoperation):  Perform a lookup to get secure operation handler for signing/verification

### **Service management functions**

* [FindService:](#findservice) Perform a service name lookup to locate a configured service.
* [CreateTask](#createtask-service-variant): Create a task for service, session, or channel operations that separates the provided object and all children from [Run](#run).

### **System management functions**

* [GetAuthenticationManager](#getauthenticationmanager): Retrieve the running authentication manager.
* [GetTelemetryManager](#gettelemetrymanager): Retrieve the running telemetry manager.
* [\~Guardian](#guardian): The destructor attempts a graceful shutdown of Guardian.
* [Shutdown](#shutdown): Clean shutdown of Guardian

## File types

Guardian uses several file types with specific extensions during the provisioning process:

**Provision Request:** File used for transmitting information including public keys to the Guardian Cloud backend. This contains the Certificate Signing Requests (CSRs) sent to Guardian Cloud. Extension: `.mcpr`

**TrustStore:** Trust anchors for the Guardian platform. Extension: `.mcts`

**Profile files:**

1. **Certified Profile to be Provisioned:** Signed instructions and configuration for the Guardian library and provisioning operations. This is the initial profile template for this device type created during the provisioning process. Extension: `.mcpp`
2. **Certified Profile:** Signed instructions and configuration for the Guardian library run and reprovisioning operations. This is the final device profile created during the provisioning process. Extension: `.mcp`

**Identity files:**&#x20;

1. **Private Identity to be Provisioned:** Key material for initial provisioning operations and connections. This is the initial private identity template. Extension: `.mcpip`
2. **Private Identity:** Key material for reprovisioning and run operations and connections. This is the final private identity file, which contains the private keys that stay on the device. Extension: `.mcpi`

* **Certificate Revocation List:** Revoked certificates are included in the `.mccrl` file.

## Device setup and provisioning workflow

These steps cover the core provisioning functions for Guardian.

### Step 1: Create Guardian instance

The `Guardian()`  function creates a new Guardian instance and puts it into startup state, ready for initialization. Refer to [Guardian function](https://docs.medcrypt.com/api-reference/api-overview#guardian) for more details.

### Step 2: Initialize Guardian

The `Initialize()` function initializes Guardian with device credentials and configuration files. It uses the provided profile, identity, and trust files to initialize the guardian system. Refer to [Initialize function](https://docs.medcrypt.com/api-reference/api-overview#initialize) for more details.

### Step 3: Generate device provisioning request

The `GenerateProvisionRequest()` function creates a provisioning request for establishing device identity. Refer to [GenerateProvisionRequest function](https://docs.medcrypt.com/api-reference/api-overview#generateprovisionrequest) for more details.

### Step 4: Submit & process provision request

The `StartProvisioningOnline()` function starts the online provisioning process for connected devices to submit a provisioning request to Guardian Cloud.

### Step 5: Monitor provisioning & retrieve device's certified profile

1. Call `Run()` repeatedly to process provisioning tasks
2. Call `IsProvisioningRunning()` to check if provisioning is complete
3. When `IsProvisioningRunning()` returns false, call `GetProvisionedProfile()` to retrieve the certified profile

Refer to [request processing functions](https://docs.medcrypt.com/api-reference/api-overview#run) for more details.

## Debugging and logging

Guardian does not create log files. Instead, logging is controlled by the application:

* Guardian logs to `stdout` and `stderr`, which appear in the terminal/CLI of the running application during execution. Look for specific error codes or connection failures in the output.
* **Custom logging:** Use `SetLoggingCallback` to redirect log messages to a callback function, stopping terminal output and allowing custom log handling
* **Log control:** Applications can control log level and verbosity.
* **Guardian Cloud UI**: Check the Guardian Cloud interface for additional error details and provisioning status.
