Tutorial: Connect New Device
This tutorial will show you how to connect a Device. You will:
- Create a Provisioning Token
- Start a Provision Operation
- Approve the Device
Requirements
- PC or any other machine with either Linux or Windows.
- One of the following:
- Python of version ≥ 3.7
- C compiler (examples use GCC with Make on Linux and Visual Studio 2022 on Windows)
- Rust
- If you are not registered to the Spotflow IoT Platform yet, Sign Up.
- You need to have an existing Workspace.
1. Create Provisioning Token
The process used to register a Device to the Platform is called Device Provisioning. To perform it, the Device needs a Provisioning Token. Let's create it:
- Portal
- CLI
- API
Open the link Devices in the left sidebar.
The list of all connected Devices opens. The Device will appear here after you register it to the Platform. Open the link Tokens in the left sidebar.
The list of Provisioning Tokens opens. Click Create new in the upper right corner.
Use the Recommended Registration Token Lifetime. Click Next.
Keep the default configuration of how Devices obtain their IDs. Click Next.
Enter an arbitrary name (e.g.,
Test Token
) and click Create.The newly created Provisioning Token appears at the bottom of the page. Click the copy icon on the right side to copy it to the clipboard. Note it somewhere so that you can use it in the next step.
Supposing you have already installed the CLI and logged in, run the following command:
spotf provisioning-token create --display-name "Test Token"
The CLI will confirm the creation and display the Provisioning Token details:
ProvisioningTokenId: 49ea58cf-6a87-413a-b8c4-e8dd1d364006
ProvisioningToken: CAEQAQ.ChIJLjh59NiNOU4RgC2QjaoFuRA.eYt-EUvBDsmhsF-s1TBR6B8dI2BtdIiwjOoGfPpLSVn9SC8n35nWi03d36XqZ2Yp9Caj6d6v8XTKIhQ6g0R731mIxNaNh2Gt-4zFccJsNV956IBmHYblUUHO1YcS-NsP
IssuedTime: 2023-10-23T12:50:17.9088245+00:00
RegistrationTokenLifetimeOverrideMode: Allowed
DeviceIdOverrideMode: DeviceAndTechnicianAllow
AllowInfiniteRegistrationTokenLifetime: false
MaxRegistrationTokenLifetime: 30d
Note the value following the label ProvisioningToken:
somewhere so you can use it in the next step.
The following instructions expect that you have already obtained the API access token from the Portal and that you know the Workspace ID.
Replace the placeholders <Your Workspace ID>
and <Your API Access Token>
with your Workspace ID and API access token and run the following command to create a new Provisioning Token:
- cURL
- PowerShell
curl -X POST 'https://api.eu1.spotflow.io/workspaces/<Your Workspace ID>/provisioning-tokens/create' \
-H 'Content-Type: application/json' \
-H 'Accept: application/json' \
-H 'Authorization: Bearer <Your API Access Token>' \
-d '{"displayName": "Test Token", "maxRegistrationTokenLifetime": "30.00:00:00", "registrationTokenLifetimeOverrideMode": "Allowed", "deviceIdOverrideMode": "DeviceAndTechnicianAllow", "allowInfiniteRegistrationTokenLifetime": false}'
(Invoke-WebRequest -Method Post -Uri 'https://api.eu1.spotflow.io/workspaces/<Your Workspace ID>/provisioning-tokens/create' `
-Headers @{
'Content-Type' = 'application/json'
'Accept' = 'application/json'
'Authorization' = 'Bearer <Your API Access Token>'
} `
-Body '{"displayName": "Test Token", "maxRegistrationTokenLifetime": "30.00:00:00", "registrationTokenLifetimeOverrideMode": "Allowed", "deviceIdOverrideMode": "DeviceAndTechnicianAllow", "allowInfiniteRegistrationTokenLifetime": false}').Content
The API will confirm the creation and display the Provisioning Token details:
{
"provisioningTokenId": "49ea58cf-6a87-413a-b8c4-e8dd1d364006",
"provisioningToken": "CAEQAQ.ChIJLjh59NiNOU4RgC2QjaoFuRA.eYt-EUvBDsmhsF-s1TBR6B8dI2BtdIiwjOoGfPpLSVn9SC8n35nWi03d36XqZ2Yp9Caj6d6v8XTKIhQ6g0R731mIxNaNh2Gt-4zFccJsNV956IBmHYblUUHO1YcS-NsP",
"issuedTime": "2023-10-23T12:50:17.9088245+00:00",
"maxRegistrationTokenLifetime": "30d",
"registrationTokenLifetimeOverrideMode": "Allowed",
"deviceIdOverrideMode": "DeviceAndTechnicianAllow",
"allowInfiniteRegistrationTokenLifetime": false
}
Note the value of the property provisioningToken
somewhere so that you can use it in the next step.
2. Start Provisioning Operation
Use the Provisioning Token to start a Provisioning Operation.
- Python
- C
- Rust
Install the recent Device SDK for Python using the following command:
pip install --upgrade spotflow-device
Paste the following code into a new file, or download it.
Replace the placeholder <Your Provisioning Token>
with your Provisioning Token and run the program.
from spotflow_device import DeviceClient
import time
# Connect to the Platform (starts Device Provisioning if the Device is not already registered)
client = DeviceClient.start(device_id="my-device", provisioning_token="<Your Provisioning Token>", db="spotflow.db")
while True:
print("While the code runs, the device with ID '" + client.device_id + "' keeps connected to the platform.")
# Your working code should be here.
time.sleep(5)
DeviceClient.start
will display the Provisioning Operation ID and Verification Code:
Provisioning operation initialized, waiting for approval.
Operation ID: b170c9ab-961c-4c02-af88-d4287d9cea1f
Verification Code: 3cwz1g1c
Download the latest version of the Spotflow Device SDK library for your operating system and processor architecture:
Download start_provisioning_operation.c.
Extract the archive to a directory of your choice.
Replace the contents of examples/get_started.c
with the contents of start_provisioning_operation.c
you just dowloaded, it contains the following code:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "spotflow.h"
#ifdef _WIN32
#include <windows.h>
#else
#include <unistd.h>
#define Sleep(x) usleep((x)*1000)
#endif
void show_last_error()
{
size_t error_size = SPOTFLOW_ERROR_MAX_LENGTH;
char* error_buffer = malloc(error_size);
spotflow_read_last_error_message(error_buffer, error_size);
printf("Error: %s\n", error_buffer);
free(error_buffer);
}
int main()
{
spotflow_client_options_t* options;
spotflow_client_options_create(&options, "spotflow.db", "<Your Provisioning Token>", "my-device");
spotflow_client_t* client;
if (spotflow_client_start(&client, options) != SPOTFLOW_OK)
{
show_last_error();
return 1;
}
while (1)
{
printf("While the code runs, the device with ID 'my-device' keeps connected to the platform.\n");
Sleep(5000);
}
spotflow_client_destroy(client);
spotflow_client_options_destroy(options);
}
Replace the placeholder <Your Provisioning Token>
with your Provisioning Token and run the program:
- Linux
- Windows
Make sure that you have gcc
and make
installed.
Navigate to the directory examples/gcc_makefile_dynamic
and run the following command:
make run
Open the solution examples/vs2022_dynamic/spotflow_example.sln
in Visual Studio 2022.
Press F5 or Debug > Start Debugging to build and run the example program.
spotflow_client_start
will display the Provisioning Operation ID and Verification Code:
Provisioning operation initialized, waiting for approval.
Operation ID: b170c9ab-961c-4c02-af88-d4287d9cea1f
Verification Code: 3cwz1g1c
Run the following commands to create a new Rust project and add the crate spotflow
to the dependencies:
cargo new connect_device --bin
cd connect_device
cargo add spotflow
Replace the contents of src/main.rs
with the following code (download):
use spotflow::DeviceClientBuilder;
fn main() {
// Connect to the Platform (starts Device Provisioning if the Device is not already registered)
let provisioning_token = String::from("<Your Provisiniong Token>");
let client = DeviceClientBuilder::new(
Some(String::from("my-device")),
provisioning_token,
"spotflow.db",
)
.build()
.expect("Unable to build ingress connection");
// Wait for all the messages to be sent
loop {
println!("While the code runs, the device with ID '{}' keeps connected to the platform.", client.device_id());
// Your working code should be here.
std::thread::sleep(std::time::Duration::from_secs(5));
}
}
Replace the placeholder <Your Provisioning Token>
with your Provisioning Token and run the program:
cargo run
DeviceClientBuilder::build
will display the Provisioning Operation ID and Verification Code:
Provisioning operation initialized, waiting for approval.
Operation ID: b170c9ab-961c-4c02-af88-d4287d9cea1f
Verification Code: 3cwz1g1c
After you verify and approve the operation in the next step, the Device will be successfully registered and ready to start sending data to the Platform.
3. Approve Device
While the code on the Device side is still running, you'll now approve the Provisioning Operation started in the previous step:
- Portal
- CLI
- API
Expand the link Devices in the left sidebar if it's not already expanded. Open the link Approvals.
The list of Provisioning Operations opens. You should see a row with the Device ID
my-device
. Click Approve in the column Actions.The approval dialog window shows the Provisioning Operation details and allows you to override Device registration details. Check the Verification Code, leave the default values and click Approve.
Good job! The Device disappeared from the table because its state changed to Approved, while the current filter shows only the Devices in the state Waiting for Approval.
The following instructions expect that you have already installed the CLI and logged in.
Run the following command in a different terminal window than where the Device SDK is running.
Replace the placeholder <Your Provisioning Operation ID>
by the Operation ID
you received from the Device in the previous step.
spotf provisioning-operation approve --provisioning-operation-id <Your Provisioning Operation ID>
The CLI will confirm the Provisioning Operation approval:
Provisioning operation 'b170c9ab-961c-4c02-af88-d4287d9cea1f' approved successfully.
The following instructions expect that you have already obtained the API access token from the Portal and that you know the Workspace ID.
Replace the placeholders <Your Workspace ID>
, <Your API Access Token>
, and <Your Provisioning Operation ID>
with your Workspace ID, API access token, and Provisioning Operation ID and run the following command to approve the Provisioning Operation:
- cURL
- PowerShell
curl -X PUT 'https://api.eu1.spotflow.io/workspaces/<Your Workspace ID>/provisioning-operations/approve' \
-H 'Content-Type: application/json' \
-H 'Accept: application/json' \
-H 'Authorization: Bearer <Your API Access Token>' \
-d '{"provisioningOperationId": "<Your Provisioning Operation ID>"}' \
-w "%{http_code}"
(Invoke-WebRequest -Method Put -Uri 'https://api.eu1.spotflow.io/workspaces/<Your Workspace ID>/provisioning-operations/approve' `
-Headers @{
'Content-Type' = 'application/json'
'Accept' = 'application/json'
'Authorization' = 'Bearer <Your API Access Token>'
} `
-Body '{"provisioningOperationId": "<Your Provisioning Operation ID>"}').StatusCode
The API will return the code 201
to confirm the approval.
The Device SDK documentation provides more information about Python SDK and C SDK.
4. See Registered Device
When the Device SDK completes the registration, the Device appears in the table of all registered Devices.
- Portal
- API
Navigate to the list of registered Devices by clicking the link Devices in the left sidebar.
You should see a row in the table with the Device ID
my-device
. If you don't see it, the Device hasn't completed the registration yet. Ensure that the code on the Device side finished the registration, and click the refresh button after a few seconds. Click the Device IDmy-device
to see the details.The Device Details page is useful to inspect the Device state. The Device Connection shows whether the Device is currently connected to the Platform. In our case, the status will be Disconnected because the program is not sending any Messages.
The following instructions expect that you have already obtained the API access token from the Portal and that you know the Workspace ID.
Replace the placeholders <Your Workspace ID>
, <Your Device ID>
, and <Your API Access Token>
with your Workspace ID, your Device ID and API access token and run the following command to get the Device details:
- cURL
- PowerShell
curl -X GET 'https://api.eu1.spotflow.io/workspaces/<Your Workspace ID>/devices/<Your Device ID>/activity' \
-H 'Content-Type: application/json' \
-H 'Accept: application/json' \
-H 'Authorization: Bearer <Your API Access Token>' \
Invoke-WebRequest -Method Get -Uri 'https://api.eu1.spotflow.io/workspaces/<Your Workspace ID>/devices/<Your Device ID>/activity' `
-Headers @{
'Content-Type' = 'application/json'
'Accept' = 'application/json'
'Authorization' = 'Bearer <Your API Access Token>'
}
The API will return the code 200
and the following payload. In our case, the status will be Disconnected because the program is not sending any Messages.
{
"deviceId": "my-device",
"deviceUniqueId": "my-device",
"deviceCategory": "DirectlyConnectedDevice",
"connection": {
"status": "Disconnected"
},
"activity": {
"isActive": false,
"latest": {
"activityId": "Cloud.DeviceRegistration",
"dateTime": "2024-04-15T05:03:41.7395144+00:00"
},
"all": [
{
"activityId": "Cloud.DeviceRegistration",
"dateTime": "2024-04-15T05:03:41.7395144+00:00"
}
]
}
}
What's Next
- The following tutorial shows how to send Messages from Devices.
- The parent page Connect Devices explains the concepts of Device connection in more detail.
- The Device SDK references for Python, C, and Rust describe the interface you can use to connect Devices to the Platform.