Python code for iot hub function app
Feb 19, 2026 in Uncategorized by admin
import time
import json
import asyncio
from azure.iot.device import IoTHubDeviceClient
# Define your connection string
CONNECTION_STRING = "<YOUR_DEVICE_CONNECTION_STRING>"
# The method to send data (called every 20 minutes)
async def send_to_iot_hub_method(client, data):
try:
# Send the message using the shared client instance
await client.send_message(data)
print("Message sent to IoT Hub:", data)
except Exception as e:
print(f"Error sending message: {e}")
# The main function
def main():
print("Starting the IoT Hub Python sample...")
# 1. Initialize the client in the main method
client = IoTHubDeviceClient.create_from_connection_string(CONNECTION_STRING)
print("Waiting for commands, press Ctrl-C to exit")
try:
# Connect the client
asyncio.run(client.connect())
# Main program loop
while True:
# Generate data (example)
temperature = 25 # your data generation logic here
data = json.dumps({"temperature": temperature})
# Call the send method within the loop
asyncio.run(send_to_iot_hub_method(client, data))
# Sleep for 20 minutes (1200 seconds)
time.sleep(1200)
except KeyboardInterrupt:
print("IoTHubDeviceClient sample stopped by user")
finally:
# 2. Shut down the client in the finally block for a graceful exit
print("Shutting down IoT Hub Client")
asyncio.run(client.shutdown()) # Use await client.shutdown() in an async context
if __name__ == '__main__':
main()