Skip to content

Instantly share code, notes, and snippets.

@jimbobbennett
Last active July 1, 2022 23:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jimbobbennett/165814097dbbb75e2f39b80b1d7faaf0 to your computer and use it in GitHub Desktop.
Save jimbobbennett/165814097dbbb75e2f39b80b1d7faaf0 to your computer and use it in GitHub Desktop.
Sample code to connect to Azure IoT Central using the Python SDK
import os
from dotenv import load_dotenv
from azure.iot.device.aio import IoTHubDeviceClient, ProvisioningDeviceClient
# Load the environment variables
load_dotenv()
# Get the connection details from the .env file for Azure IoT Central
ID_SCOPE = os.environ['ID_SCOPE']
DEVICE_ID = os.environ['DEVICE_ID']
PRIMARY_KEY = os.environ['PRIMARY_KEY']
async def connect_device() -> IoTHubDeviceClient:
"""Connects this device to IoT Central
"""
# Connect to the device provisioning service and request the connection details
# for the device
provisioning_device_client = ProvisioningDeviceClient.create_from_symmetric_key(
provisioning_host='global.azure-devices-provisioning.net',
registration_id=DEVICE_ID,
id_scope=ID_SCOPE,
symmetric_key=PRIMARY_KEY)
registration_result = await provisioning_device_client.register()
# Build the connection string - this is used to connect to IoT Central
conn_str = 'HostName=' + registration_result.registration_state.assigned_hub + \
';DeviceId=' + DEVICE_ID + \
';SharedAccessKey=' + PRIMARY_KEY
# The device client object is used to interact with Azure IoT Central.
device_client = IoTHubDeviceClient.create_from_connection_string(conn_str)
# Connect to the IoT Central hub
device_client.connect()
# Return the device client
return device_client
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment