36 lines
1.2 KiB
Python
36 lines
1.2 KiB
Python
from azure.iot.device import IoTHubDeviceClient, Message
|
|
import time
|
|
import random
|
|
|
|
|
|
# ENTER CONNECTION STRING FROM AZURE IOT HUB
|
|
CONNECTION_STRING = "HostName=ESP32-IoTHub.azure-devices.net;DeviceId=Simulated-ESP32;SharedAccessKey=hGbt7EnzeJDtfCirbRuNVLr/6AMSXyLgVqTo4DNlTuI="
|
|
# Creating client to connect Azure IoT Hub using connection string
|
|
client = IoTHubDeviceClient.create_from_connection_string(CONNECTION_STRING)
|
|
|
|
|
|
print("Simulated ESP32 is sending data to Azure IOT HUB...")
|
|
|
|
try:
|
|
while True:
|
|
# Random simulated data
|
|
temperature = round(random.uniform(20, 30), 2) # Random temperature (20 to 30 Celcius)
|
|
humidity = round(random.uniform(40, 60), 2) # Random humidity (40 to 60 %)
|
|
|
|
# Create JSON-formatted message to send IoT Hub
|
|
message = Message(f'{{"temperature": {temperature}, "humidity": {humidity}}}')
|
|
|
|
# Send message to Azure IoT Hub
|
|
client.send_message(message)
|
|
print(f"Sent: {message}")
|
|
|
|
# 5 second delay before sending next message
|
|
time.sleep(5)
|
|
|
|
except KeyboardInterrupt:
|
|
# If user stops the script (Ctrl+C), print message and clean up
|
|
print("Stopped sending data.")
|
|
|
|
finally:
|
|
# Shut down IoT Hub client
|
|
client.shutdown() |