Package: iotc
Microsoft Azure IoTCentral SDK for PythonAn Azure IoT Central device client library written in Python.This repository contains code for the Azure IoT Central SDK for Python. This enables python developers to easily create device solutions that semealessly connect to Azure IoT Central applications.
It hides some of the complexities of the official Azure IoT SDK and uses IoT Central naming conventions.DisclaimerThis library is experimental and has the purpose of providing an easy to use solution for prototyping and small projects. Its use in production is discouraged.
The library is going to be archived soon so we suggest new developments to start using official Azure IoT SDK.Please refer toAzure IoT Python SDKwhen building production products.If you're looking for the v0.x.x client library, it is now preservedhere.
Latest version on pypi is 0.3.9PrerequisitesPython 2.7+ or Python 3.7+ (recommended)Installingiotcpip install iotcThese clients are available with an asynchronous API, as well as a blocking synchronous API for compatibility scenarios.We recommend you use Python 3.7+ and the asynchronous API.Python VersionAsynchronous APISynchronous APIPython 3.5.3+YESYESPython 2.7NOYESSamplesCheck out thesample repositoryfor example code showing how the SDK can be used in the various scenarios:async_device_key- Sending telemetry and receiving properties and commands with device connected throughsymmetric key(Python 3.7+)async_x509- Sending telemetry and receiving properties and commands with device connected throughx509 certificates(Python 3.7+)async_file_logger- Print logs on file with rotation (Python 3.7+)async_eventhub_logger- Redirect logs to Azure Event Hub (Python 3.7+)The following samples are legacy samples, they work with the sycnhronous API intended for use with Python 2.7, or in compatibility scenarios with later versions. We recommend you use the asynchronous API and Python3 samples above instead.sync_device_key- Sending telemetry and receiving properties and commands with device connected throughsymmetric key(Python 2.7+)sync_x509- Sending telemetry and receiving properties and commands with device connected throughx509 certificates(Python 2.7+)Samples by default parse a configuration file including required credentials. Just create a file calledsamples.iniinside thesamplesfolder with a content like this:[DEVICE_A]ScopeId=scopeidDeviceId=deviceid; either one or the other or nothing if running with certificatesDeviceKey=device_keyGroupKey=group_key; none if running with keysCertFilePath=path_to_cert_fileKeyFilePath=path_to_key_fileCertPassphrase=optional passwordThe configuration file can include one or more sections representing device connection details. Section names must match references in the sample file.Run samples with local changesIt is possible to run samples against the local copy of the device client. This is particularly useful when testing patches not yet published upstream.
Just add an entry tosamples.iniin theDEFAULTsection:[DEFAULT]Local=yesImporting the moduleSync client (Python 2.7+ and 3.7+) can be imported in this way:fromiotcimportIoTCClientAsync client (with asyncio for Python 3.7+ only) can be imported like this:fromiotc.aioimportIoTCClientConnectingX509scope_id='scope_id';device_id='device_id';key={'certFile':'<CERT_CHAIN_FILE_PATH>','keyFile':'<CERT_KEY_FILE_PATH>','certPhrase':'<CERT_PASSWORD>'}iotc=IoTCClient(device_id,scope_id,IOTCConnectType.IOTC_CONNECT_X509_CERT,key)IOTCConnectType enum can be imported from the same module of IoTCClient'certPhrase'is optional and represents the password for the certificate if anyA handy tool to generate self-signed certificates in order to test x509 authentication can be found in the IoTCentral Node.JS SDKhere.SASscopeId='scopeID'device_id='device_id'sasKey='masterKey'# or use device key directlyiotc=IoTCClient(device_id,scopeId,IOTCConnectType.IOTC_CONNECT_SYMM_KEY,sas_key)IOTCConnectType enum can be imported from the same module of IoTCClientConnectSynciotc.connect()Asyncawaitiotc.connect()After successfull connection, IOTC context is available for further commands.ReconnectionThe device client automatically handle reconnection in case of network failures or disconnections. However if process runs for long time (e.g. unmonitored devices) a reconnection might fail because of credentials expiration.To control reconnection and reset credentials the functionis_connected()is available and can be used to test connection status inside a loop or before running operations.e.g.retry=0# stop reconnection attemptswhiletrue:ifiotc.is_connected():# do somethingelseifretry==10:sys.exit("error")retry+=1iotc.connect()Cache CredentialsThe IoT Central device client accepts a storage manager to cache connection credentials. This allows to skip unnecessary device re-provisioning and requests to provisioning service.
When valid credentials are present, device connects directly to IoT Central, otherwise it asks provisioning service for new credentials and eventually cache them.Provided class must extendStorageabstract class.classFileStorage(Storage):def__init__(self):# initialize file read...defretrieve(self):# read from file...returnCredentialsCache(hub_name,device_id,key,)defpersist(self,credentials):# write to file...OperationsSend telemetrye.g. Send telemetry every 3 secondswhileiotc.is_connected():awaitiotc.send_telemetry({'accelerometerX':str(randint(20,45)),'accelerometerY':str(randint(20,45)),"accelerometerZ":str(randint(20,45))})time.sleep(3)An optionalpropertiesobject can be included in the send methods, to specify additional properties for the message (e.g. timestamp,etc... ).
Properties can be custom or part of the reserved ones (see listhere).Payload content type and encoding are set by default to 'application/json' and 'utf-8'. Alternative values can be set using these functions:iotc.set_content_type(content_type)# .e.g 'text/plain'iotc.set_content_encoding(content_encoding)# .e.g 'ascii'Send property updateiotc.send_property({'fieldName':'fieldValue'})Listen to properties updateiotc.on(IOTCEvents.IOTC_PROPERTIES,callback)To provide setting sync aknowledgement, the callback must replyTrueif the new value has been applied orFalseotherwiseasyncdefon_props(prop_name,prop_value):print(prop_value)returnTrueiotc.on(IOTCEvents.IOTC_PROPERTIES,on_props)Listen to commandsiotc.on(IOTCEvents.IOTC_COMMAND,callback)To provide feedbacks for the command like execution result or progress, the client can call theackfunction available in the callback.The function accepts 3 arguments: command name, a custom response message and the request id for which the ack applies.asyncdefon_commands(command,ack):print(command.name)awaitack(command.name,'Command received',command.request_id)LoggingThe default log prints to console operations status and errors.
This is theIOTC_LOGGING_API_ONLYlogging level.
The functionset_log_level()can be used to change options or disable logs. It accepts aIOTCLogLevelvalue among the following:IOTC_LOGGING_DISABLED (log disabled)IOTC_LOGGING_API_ONLY (information and errors, default)IOTC_LOGGING_ALL (all messages, debug and underlying errors)The device client also accepts an optional Logger instance to redirect logs to other targets than console.
The custom class must implement three methods:info(message)debug(message)set_log_level(message);One-touch device provisioning and approvalA device can send custom data during provision process: if a device is aware of its IoT Central template Id, then it can be automatically provisioned.How to set IoTC template ID in your deviceTemplate Id can be found in the device explorer page of IoTCentralThen call this method before connect():iotc.set_model_id('<modelId>')Manual approval (default)By default device auto-approval in IoT Central is disabled, which means that administrator needs to approve the device registration to complete the provisioning process.
This can be done from explorer page after selecting the deviceAutomatic approvalTo change default behavior, administrator can enable device auto-approval from Device Connection page under the Administration section.
With automatic approval a device can be provisioned without any manual action and can start sending/receiving data after status changes to "Provisioned"LicenseThis samples is licensed with the MIT license. For more information, seeLICENSE