-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbridge.py
More file actions
67 lines (58 loc) · 2.3 KB
/
bridge.py
File metadata and controls
67 lines (58 loc) · 2.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
from azure.iot.device import ProvisioningDeviceClient, IoTHubDeviceClient
import time
# DPS settings
ID_SCOPE = "<ID-scope>" # Replace with your ID Scope
DEVICE_ID = "<device-ID>" # Replace with your Device ID
DEVICE_KEY = "<device-key>" # Replace with your Device Key
PROVISIONING_HOST = "global.azure-devices-provisioning.net" # DPS global endpoint
# Function to initialize the IoT Hub client
def create_client():
# Create a provisioning client
provisioning_client = ProvisioningDeviceClient.create_from_symmetric_key(
provisioning_host=PROVISIONING_HOST,
registration_id=DEVICE_ID,
id_scope=ID_SCOPE,
symmetric_key=DEVICE_KEY
)
print("Registering device...")
registration_result = provisioning_client.register()
if registration_result.status == "assigned":
print("Device successfully registered!")
print(f"Assigned IoT Hub HostName: {registration_result.registration_state.assigned_hub}")
# Use the assigned IoT Hub HostName to create an IoT Hub device client
client = IoTHubDeviceClient.create_from_symmetric_key(
symmetric_key=DEVICE_KEY,
hostname=registration_result.registration_state.assigned_hub,
device_id=DEVICE_ID
)
client.connect()
print("IoT Hub client connected successfully!")
return client
else:
raise Exception(f"Device registration failed: {registration_result.status}")
# Main function
def main():
client = None
try:
# Create and connect the client
client = create_client()
print("Client is now running. Sending messages...")
while True:
# Simulate sending data
message = '{"temperature": 22.5, "humidity": 60}' # Replace with actual sensor data
print(f"Sending message: {message}")
client.send_message(message)
print("Message sent successfully!")
# Wait before sending the next message
time.sleep(10) # Send every 10 seconds (adjust as needed)
except KeyboardInterrupt:
print("Exiting...")
except Exception as e:
print(f"An error occurred: {e}")
finally:
if client:
print("Shutting down client...")
client.shutdown()
# Run the script
if __name__ == "__main__":
main()