请求
失败:HTTPSConnectionPool(主机='ih1-das-pr-1wp.azure-devices.net',端口=443):超过最大重试次数,网址:/devices/R0664654-1WP/messages/events/?api-version- 2018-86-30
(由 NewConnectionError 引起('
我尝试连接到 Azure IoT 中心发送消息,但遇到“没有到主机的路由”错误。我期望连接成功,但多次重试后失败,可能是由于网络问题或防火墙设置。
我尝试将示例代码与您在问题中提供的 REST API 一起使用,但收到了相同的错误,如下所示:
我参考了有关通过 REST API 将设备事件发送到 Azure IoT 中心的文档。
此外,我查阅了有关为 Azure IoT 中心生成共享访问签名的文档。
下面是使用 REST API 将遥测数据发送到 Azure IoT 中心的 Python 代码。
import requests
import json
iot_hub_name = 'AzureIotHubName.azure-devices.net'
device_id = 'AzureDeviceId'
api_version = '2020-03-13'
sas_token = 'SharedAccessSignature sr=...'
url = f'https://{iot_hub_name}/devices/{device_id}/messages/events?api-version={api_version}'
payload = {
"Temperature": 54
}
headers = {
'Authorization': sas_token,
'Content-Type': 'application/json'
}
try:
response = requests.post(url, headers=headers, data=json.dumps(payload))
# Check if the request was successful
if response.status_code == 204:
print("Telemetry data sent successfully! (204 No Content)")
else:
print(f"Failed to send telemetry data. Status code: {response.status_code}")
print(f"Response: {response.text}")
except requests.exceptions.RequestException as e:
print(f"An error occurred: {e}")
输出:
az iot hub monitor-events
命令用于监控发送到 IoT 中心的设备到云消息(遥测)。您可以在 Azure CLI 中运行以下命令来实时监控事件:
az iot hub monitor-events --hub-name `IoTHubName` --output json