# -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------
import
os
asyncio
threading
from
six.moves
input
azure.iot.device.aio
IoTHubDeviceClient
azure.iot.device
MethodResponse
async
def
main():
# The connection string for your device.
conn_str
=
"HostName=***.azure-devices.net;DeviceId=***;SharedAccessKey=***"
# The client object is used to interact with your Azure IoT hub.
device_client
IoTHubDeviceClient.create_from_connection_string(conn_str)
# connect the client.
await device_client.connect()
# define behavior for handling methods
method1_listener(device_client):
while
True
:
method_request
await device_client.receive_method_request(
"method1"
)
# Wait for method1 calls
payload
{
"result"
,
"data"
"execute successfully"
}
# set response payload
status
200
# set return status code
print
(
"executed method1"
method_response
MethodResponse.create_from_method_request(
method_request, status, payload
await device_client.send_method_response(method_response)
# send response
method2_listener(device_client):
"method2"
# Wait for method2 calls
1234
"executed method2"
generic_method_listener(device_client):
await device_client.receive_method_request()
# Wait for unknown method calls
False
"unknown method"
400
"executed unknown method: "
+
method_request.name)
# define behavior for halting the application
stdin_listener():
selection
input(
"Press Q to quit\n"
if
"Q"
or
"q"
"Quitting..."
break
# Schedule tasks for Method Listener
listeners
asyncio.gather(
method1_listener(device_client),
method2_listener(device_client),
generic_method_listener(device_client),
# Run the stdin listener in the event loop
loop
asyncio.get_running_loop()
user_finished
loop.run_in_executor(
None
, stdin_listener)
# Wait for user to indicate they are done listening for method calls
await user_finished
# Cancel listening
listeners.cancel()
# Finally, disconnect
await device_client.disconnect()
__name__
"__main__"
asyncio.run(main())
# If using Python 3.6 or below, use the following code instead of asyncio.run(main()):
# loop = asyncio.get_event_loop()
# loop.run_until_complete(main())
# loop.close()