Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

(GH-182) Add example of device managing device twin in Python #425

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 53 additions & 0 deletions resources/code-template/python/deviceManageDeviceTwin.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
# Copyright (c) Microsoft. All rights reserved.
# Licensed under the MIT license. See LICENSE file in the project root for full license information.

import random
import time
import sys

# Using the Python Device SDK for IoT Hub:
# https://github.com/Azure/azure-iot-sdk-python
# Run 'pip install azure-iot-device' to install the required libraries for this application

import asyncio
from azure.iot.device.aio import IoTHubDeviceClient

# The device connection string to authenticate the device with your IoT hub.
CONNECTION_STRING = "{{deviceConnectionString}}"

async def manage_device_twin_sample_run():
try:
# Create instance of the device client using the authentication provider
device_client = IoTHubDeviceClient.create_from_connection_string(CONNECTION_STRING)

# Connect the device client.
await device_client.connect()

print ( "Get device twin" )
twin = await device_client.get_twin()
print (twin)

print ( "Updating reported properties" )
reported_properties_patch = {
"weather": {
"temperature": 72,
"humidity": 17
},
"firmwareVersion": "1.2.2"
}
await device_client.patch_twin_reported_properties(reported_properties_patch)

except Exception as iothub_error:
print ( "Unexpected error %s from IoTHub" % iothub_error )
finally:
print ( "Disconnecting client" )
await device_client.disconnect()

if __name__ == '__main__':
print ( "IoT Hub simulated device" )
asyncio.run(manage_device_twin_sample_run())

# If using Python 3.6 or below, use the following code instead of asyncio.run(manage_device_twin_sample_run()):
# loop = asyncio.get_event_loop()
# loop.run_until_complete(manage_device_twin_sample_run())
# loop.close()
1 change: 1 addition & 0 deletions src/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -179,6 +179,7 @@ export class Constants {
},
[TemplateLanguage.Python]: {
[TemplateType.SendD2C]: "python/sendD2C.py",
[TemplateType.DeviceManageDeviceTwin]: "python/deviceManageDeviceTwin.py"
},
[TemplateLanguage.Ruby]: {
[TemplateType.SendD2C]: "ruby/sendD2C.rb",
Expand Down