{"id":25965849,"url":"https://github.com/iot-for-all/iotc-python-client","last_synced_at":"2025-03-04T22:01:55.571Z","repository":{"id":46187976,"uuid":"271587967","full_name":"Azure/iot-central-python-client","owner":"Azure","description":"A Python SDK for connecting devices to Microsoft Azure IoT Central","archived":false,"fork":false,"pushed_at":"2022-10-20T17:27:12.000Z","size":453,"stargazers_count":6,"open_issues_count":1,"forks_count":9,"subscribers_count":9,"default_branch":"master","last_synced_at":"2025-02-26T09:42:53.281Z","etag":null,"topics":["iot","iot-central","python"],"latest_commit_sha":null,"homepage":"","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/Azure.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":"SECURITY.md","support":null}},"created_at":"2020-06-11T15:55:48.000Z","updated_at":"2023-02-11T14:30:27.000Z","dependencies_parsed_at":"2022-08-12T12:40:56.562Z","dependency_job_id":null,"html_url":"https://github.com/Azure/iot-central-python-client","commit_stats":null,"previous_names":["iot-for-all/iotc-python-client"],"tags_count":2,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Azure%2Fiot-central-python-client","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Azure%2Fiot-central-python-client/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Azure%2Fiot-central-python-client/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Azure%2Fiot-central-python-client/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/Azure","download_url":"https://codeload.github.com/Azure/iot-central-python-client/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":241928529,"owners_count":20043821,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["iot","iot-central","python"],"created_at":"2025-03-04T22:00:48.595Z","updated_at":"2025-03-04T22:01:55.561Z","avatar_url":"https://github.com/Azure.png","language":"Python","funding_links":[],"categories":["miscellaneous"],"sub_categories":[],"readme":"# Microsoft Azure IoTCentral SDK for Python\n\n[![Join the chat at https://gitter.im/iotdisc/community](https://badges.gitter.im/iotdisc.svg)](https://gitter.im/iotdisc/community?utm_source=badge\u0026utm_medium=badge\u0026utm_campaign=pr-badge\u0026utm_content=badge)\n[![Licensed under the MIT License](https://img.shields.io/badge/License-MIT-blue.svg)](https://github.com/lucadruda/iotc-python-device-client/blob/master/LICENSE)\n[![PyPI version](https://badge.fury.io/py/iotc.svg)](https://badge.fury.io/py/iotc)\n\n### An Azure IoT Central device client library written in Python.\n\nThis 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.\nIt hides some of the complexities of the official Azure IoT SDK and uses IoT Central naming conventions.\n\n### Disclaimer\n\n\u003e **This 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.\nThe library is going to be archived soon so we suggest new developments to start using official Azure IoT SDK.**\n\n\u003e **Please refer to [Azure IoT Python SDK](https://github.com/Azure/azure-iot-sdk-python) when building production products.**\n\n_If you're looking for the v0.x.x client library, it is now preserved [here](https://github.com/obastemur/iot_client/tree/master/python).\nLatest version on pypi is 0.3.9_\n\n## Prerequisites\n\n- Python 2.7+ or Python 3.7+ (recommended)\n\n## Installing `iotc`\n\n```\npip install iotc\n```\n\nThese 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.**\n\n| Python Version | Asynchronous API | Synchronous API |\n| -------------- | ---------------- | --------------- |\n| Python 3.5.3+  | **YES**          | **YES**         |\n| Python 2.7     | NO               | **YES**         |\n\n## Samples\n\nCheck out the [sample repository](samples) for example code showing how the SDK can be used in the various scenarios:\n\n- [async_device_key](samples/async_device_key.py) - Sending telemetry and receiving properties and commands with device connected through **symmetric key** (Python 3.7+)\n- [async_x509](samples/async_x509.py) - Sending telemetry and receiving properties and commands with device connected through **x509 certificates** (Python 3.7+)\n- [async_file_logger](samples/async_file_logger.py) - Print logs on file with rotation (Python 3.7+)\n- [async_eventhub_logger](samples/async_eventhub_logger.py) - Redirect logs to Azure Event Hub (Python 3.7+)\n\n**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.\n\n- [sync_device_key](samples/sync_device_key.py) - Sending telemetry and receiving properties and commands with device connected through **symmetric key** (Python 2.7+)\n- [sync_x509](samples/sync_x509.py) - Sending telemetry and receiving properties and commands with device connected through **x509 certificates** (Python 2.7+)\n\nSamples by default parse a configuration file including required credentials. Just create a file called **samples.ini** inside the _samples_ folder with a content like this:\n\n```ini\n[DEVICE_A]\nScopeId = scopeid\nDeviceId = deviceid\n; either one or the other or nothing if running with certificates\nDeviceKey = device_key\nGroupKey = group_key\n; none if running with keys\nCertFilePath = path_to_cert_file\nKeyFilePath = path_to_key_file\nCertPassphrase = optional password\n```\n\nThe configuration file can include one or more sections representing device connection details. Section names must match references in the sample file.\n\n### Run samples with local changes\n\nIt is possible to run samples against the local copy of the device client. This is particularly useful when testing patches not yet published upstream.\nJust add an entry to **samples.ini** in the _DEFAULT_ section:\n\n```ini\n[DEFAULT]\nLocal = yes\n```\n\n## Importing the module\n\nSync client (Python 2.7+ and 3.7+) can be imported in this way:\n\n```py\nfrom iotc import IoTCClient\n```\n\nAsync client (with asyncio for Python 3.7+ only) can be imported like this:\n\n```py\nfrom iotc.aio import IoTCClient\n```\n\n## Connecting\n\n#### X509\n\n```py\nscope_id = 'scope_id';\ndevice_id = 'device_id';\nkey = {'certFile':'\u003cCERT_CHAIN_FILE_PATH\u003e','keyFile':'\u003cCERT_KEY_FILE_PATH\u003e','certPhrase':'\u003cCERT_PASSWORD\u003e'}\n\niotc = IoTCClient(device_id, scope_id,\n                  IOTCConnectType.IOTC_CONNECT_X509_CERT, key)\n```\n\nIOTCConnectType enum can be imported from the same module of IoTCClient\n\n_'certPhrase'_ is optional and represents the password for the certificate if any\n\n**_A handy tool to generate self-signed certificates in order to test x509 authentication can be found in the IoTCentral Node.JS SDK [here.](https://github.com/lucadruda/iotc-nodejs-device-client#generate-x509-certificates)_**\n\n#### SAS\n\n```py\nscopeId = 'scopeID'\ndevice_id = 'device_id'\nsasKey = 'masterKey' # or use device key directly\n\niotc = IoTCClient(device_id, scopeId,\n                  IOTCConnectType.IOTC_CONNECT_SYMM_KEY, sas_key)\n```\n\nIOTCConnectType enum can be imported from the same module of IoTCClient\n\n### Connect\n\nSync\n\n```\niotc.connect()\n```\n\nAsync\n\n```py\nawait iotc.connect()\n```\n\nAfter successfull connection, IOTC context is available for further commands.\n\n### Reconnection\n\nThe 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.\n\nTo control reconnection and reset credentials the function _is_connected()_ is available and can be used to test connection status inside a loop or before running operations.\n\ne.g.\n\n```py\nretry = 0 # stop reconnection attempts\nwhile true:\n    if iotc.is_connected():\n        # do something\n    else\n        if retry == 10:\n            sys.exit(\"error\")\n        retry += 1\n        iotc.connect()\n```\n\n## Cache Credentials\n\nThe 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.\nWhen valid credentials are present, device connects directly to IoT Central, otherwise it asks provisioning service for new credentials and eventually cache them.\n\nProvided class must extend [_Storage_](src/iotc/models.py) abstract class.\n\n```py\nclass FileStorage(Storage):\n    def __init__(self):\n        # initialize file read\n        ...\n    def retrieve(self):\n        # read from file\n        ...\n        return CredentialsCache(\n            hub_name,\n            device_id,\n            key,\n        )\n    def persist(self, credentials):\n        # write to file\n        ...\n```\n\n## Operations\n\n### Send telemetry\n\ne.g. Send telemetry every 3 seconds\n\n```py\nwhile iotc.is_connected():\n        await iotc.send_telemetry({\n            'accelerometerX': str(randint(20, 45)),\n            'accelerometerY': str(randint(20, 45)),\n            \"accelerometerZ\": str(randint(20, 45))\n        })\n        time.sleep(3)\n```\n\nAn optional _properties_ object can be included in the send methods, to specify additional properties for the message (e.g. timestamp,etc... ).\nProperties can be custom or part of the reserved ones (see list [here](https://github.com/Azure/azure-iot-sdk-csharp/blob/master/iothub/device/src/MessageSystemPropertyNames.cs#L36)).\n\n\u003e Payload content type and encoding are set by default to 'application/json' and 'utf-8'. Alternative values can be set using these functions:\u003cbr/\u003e\n\u003e _iotc.set_content_type(content_type)_ # .e.g 'text/plain'\n\u003e _iotc.set_content_encoding(content_encoding)_ # .e.g 'ascii'\n\n### Send property update\n\n```py\niotc.send_property({'fieldName':'fieldValue'})\n```\n\n### Listen to properties update\n\n```py\niotc.on(IOTCEvents.IOTC_PROPERTIES, callback)\n```\n\nTo provide setting sync aknowledgement, the callback must reply **True** if the new value has been applied or **False** otherwise\n\n```py\nasync def on_props(prop_name, prop_value):\n    print(prop_value)\n    return True\n\niotc.on(IOTCEvents.IOTC_PROPERTIES, on_props)\n```\n\n### Listen to commands\n\n```py\niotc.on(IOTCEvents.IOTC_COMMAND, callback)\n```\n\nTo provide feedbacks for the command like execution result or progress, the client can call the **ack** function available in the callback.\n\nThe function accepts 3 arguments: command name, a custom response message and the request id for which the ack applies.\n\n```py\nasync def on_commands(command, ack):\n    print(command.name)\n    await ack(command.name, 'Command received', command.request_id)\n```\n\n## Logging\n\nThe default log prints to console operations status and errors.\nThis is the _IOTC_LOGGING_API_ONLY_ logging level.\nThe function **set_log_level()** can be used to change options or disable logs. It accepts a _IOTCLogLevel_ value among the following:\n\n- IOTC_LOGGING_DISABLED (log disabled)\n- IOTC_LOGGING_API_ONLY (information and errors, default)\n- IOTC_LOGGING_ALL (all messages, debug and underlying errors)\n\nThe device client also accepts an optional Logger instance to redirect logs to other targets than console.\nThe custom class must implement three methods:\n\n- info(message)\n- debug(message)\n- set_log_level(message);\n\n## One-touch device provisioning and approval\n\nA 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.\n\n### How to set IoTC template ID in your device\n\nTemplate Id can be found in the device explorer page of IoTCentral\n![Img](https://github.com/iot-for-all/iotc-python-client/raw/master/assets/modelId.jpg)\n\nThen call this method before connect():\n\n```py\niotc.set_model_id('\u003cmodelId\u003e')\n```\n\n### Manual approval (default)\n\nBy default device auto-approval in IoT Central is disabled, which means that administrator needs to approve the device registration to complete the provisioning process.\nThis can be done from explorer page after selecting the device\n![Img](https://github.com/iot-for-all/iotc-python-client/raw/master/assets/manual_approval.jpg)\n\n### Automatic approval\n\nTo change default behavior, administrator can enable device auto-approval from Device Connection page under the Administration section.\nWith automatic approval a device can be provisioned without any manual action and can start sending/receiving data after status changes to \"Provisioned\"\n\n![Img](https://github.com/iot-for-all/iotc-python-client/raw/master/assets/auto_approval.jpg)\n\n## License\n\nThis samples is licensed with the MIT license. For more information, see [LICENSE](./LICENSE)\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fiot-for-all%2Fiotc-python-client","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fiot-for-all%2Fiotc-python-client","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fiot-for-all%2Fiotc-python-client/lists"}