如何在iot hub中向设备发布和订阅?

问题描述 投票:0回答:1

目前我正在尝试使用发布(python)将温度数据发送到我的azure iot hub,同时我正在尝试使用另一个python代码中的订阅方法读取或接收温度数据,这两个代码都通过命令提示符运行。 到目前为止,结果是要么连接到设备。我不能按照下面的图片做吗?

代码发布

    from azure.iot.device import IoTHubDeviceClient, Message
 
# Define the connection string for your device
CONNECTION_STRING = "HostName=iothub-jein02-np-eas-ua-eztr01.azure-devices.net;DeviceId=NodeMCU;SharedAccessKey=pOkHxKaDejoJUSgUU3ZdmKqG/KV3XOcbgILSX8ZDiMk="

# Create an instance of the device client using the connection string
device_client = IoTHubDeviceClient.create_from_connection_string(CONNECTION_STRING)
 
# Connect the device client
try:

    device_client.connect()

    time.sleep(5) 

    temperature = random.randint(0, 100)
    # Create message payload 
    message_payload = { "temperature": temperature } 

    # Create a message
    message = Message(str(message_payload))
 
    # Send the message to IoT Hub
    device_client.send_message(message)
    
    print("Message sent to Azure IoT Hub successfully.")
except Exception as ex:
    print ( "Unexpected error {0}" .format(ex) )

 
# Disconnect the device client
device_client.disconnect()

代码订阅

    from azure.iot.device import IoTHubDeviceClient, Message
 
# Define the connection string for your device
CONNECTION_STRING = "<your-device-connection-string>"
 
# Define the callback function to handle received messages
def message_received_callback(message):
    print("Message received from Azure IoT Hub:")
    print("    Data: {}".format(message.data))
    print("    Properties: {}".format(message.custom_properties))
 
# Create an instance of the device client using the connection string
device_client = IoTHubDeviceClient.create_from_connection_string(CONNECTION_STRING)
 
# Set the callback function for handling received messages
device_client.on_message_received = message_received_callback
 
# Connect the device client
device_client.connect()
 
# Keep the application running
input("Press Enter to exit...\n")
 
# Disconnect the device client
device_client.disconnect()
python azure mqtt publish-subscribe azure-iot-hub
1个回答
0
投票

IoT Hub 不是完整的 MQTT 代理,不适用于使用发布/订阅模型的设备到设备通信。

IoT Hub 允许您使用设备到云或云到设备的消息传递。您正在使用的设备客户端对象可用于将消息发送到云以在云中接收和处理。您使用设备客户端发送的消息无法使用设备客户端接收。

如果您看一下 https://learn.microsoft.com/en-us/azure/iot/tutorial-send-telemetry-iot-hub?toc=%2Fazure%2Fiot-hub%2Ftoc.json&bc=% 2Fazure%2Fiot-hub%2Fbreadcrumb%2Ftoc.json&pivots=programming-language-python,您将看到设备使用设备连接字符串进行连接,并且在实用程序使用集线器连接后从集线器读取消息连接字符串.

如果您正在寻找支持发布/订阅的 Azure 托管 MQTT 代理,请查看 Azure 事件网格:https://learn.microsoft.com/en-us/azure/event-grid/mqtt-overview

© www.soinside.com 2019 - 2024. All rights reserved.