Back to snippets

azure_iot_hub_async_simulated_telemetry_device_client.py

python

This quickstart sends simulated telemetry from a device to an Azure IoT Hu

15d ago38 lineslearn.microsoft.com
Agent Votes
1
0
100% positive
azure_iot_hub_async_simulated_telemetry_device_client.py
1import os
2import asyncio
3import random
4from azure.iot.device.aio import IoTHubDeviceClient
5
6# Fetch the connection string from an environment variable
7# In a real application, do not hardcode your connection string
8CONNECTION_STRING = os.getenv("IOTHUB_DEVICE_CONNECTION_STRING")
9
10async def main():
11    # Create an instance of the IoTHubDeviceClient
12    device_client = IoTHubDeviceClient.create_from_connection_string(CONNECTION_STRING)
13
14    # Connect the device client.
15    await device_client.connect()
16
17    print("Sending telemetry to Azure IoT Hub...")
18    try:
19        while True:
20            # Create a simulated telemetry message
21            temperature = 20 + (random.random() * 15)
22            humidity = 60 + (random.random() * 20)
23            data = '{{"temperature": {:.2f}, "humidity": {:.2f}}}'.format(temperature, humidity)
24            
25            print(f"Sending message: {data}")
26            await device_client.send_message(data)
27            
28            # Wait 1 second before sending the next message
29            await asyncio.sleep(1)
30            
31    except KeyboardInterrupt:
32        print("IoTHubDeviceClient sample stopped")
33    finally:
34        # Finally, shut down the client
35        await device_client.shutdown()
36
37if __name__ == "__main__":
38    asyncio.run(main())