sai
sai

Reputation: 41

how to update device twin using python?

I am currently trying to update a property in device twin using python. but unable to do it due to SSL error.

below is the code

from azure.iot.hub import IoTHubRegistryManager
import certifi
import ssl

# Connect to IoT Hub and send message to device
CONNECTION_STRING = "HostName=iothub-jein02-np-eas-ua-eztr01.azure-devices.net;SharedAccessKeyName=service;SharedAccessKey=Mmjc..."
DEVICE_ID = "NodeMCU"

'''first used this method'''
#ca_cert_path = "D:/new/cacert.pem"

'''later used this method'''
# Set the CA certificates globally
ssl_context = ssl.create_default_context(cafile=certifi.where())

try:
    # Create IoTHubRegistryManager
    registry_manager = IoTHubRegistryManager.from_connection_string(CONNECTION_STRING, connection_verify = False)
   
    # Update the desired properties
    twin = registry_manager.update_twin(DEVICE_ID, {
        "properties": {
            "desired": {
                "temp": "100"
                }
        }
    })

except Exception as ex:
    print(f"Error sending message to device: {str(ex)}")
    raise

following is the error I'm getting

msrest.exceptions.ClientRequestError: Error occurred in request., SSLError: HTTPSConnectionPool(host='iothub-jein02-np-eas-ua-eztr01.azure-devices.net', port=443): Max retries exceeded with url: /twins/NodeMCU?api-version=2021-04-12 (Caused by SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:997)')))

Also, how to do this in 443 port (open port) it tried connection_verify = False. it says connection_verify command error

how to rectify this errors.

Upvotes: 0

Views: 140

Answers (1)

Sampath
Sampath

Reputation: 3639

The below code is to update the desired properties of an IoT device twin in Azure IoT Hub using the Azure IoT Python SDK

Install the below package using pip,

pip install azure-iot-hub

It updates the desired property of your IoT device twin to set temp to "100"

I used this MSDOC to Understand and use device twins in IoT Hub


import sys
from azure.iot.hub import IoTHubRegistryManager
from azure.iot.hub.models import Twin, TwinProperties


IOTHUB_CONNECTION_STRING = "<iot-hub-connection-string>"
DEVICE_ID = "<device-id>"

iothub_registry_manager = IoTHubRegistryManager(IOTHUB_CONNECTION_STRING)

try:
    
    twin = iothub_registry_manager.get_twin(DEVICE_ID)

 
    desired = {
        "temp": "100"
    }

   
    twin_patch = Twin(properties=TwinProperties(desired=desired))

    
    updated_twin = iothub_registry_manager.update_twin(DEVICE_ID, twin_patch, twin.etag)

    print("Desired property 'temp' set to '100' successfully.")
except Exception as ex:
    print("Unexpected error:", ex)

Output: enter image description here

Device twin:

enter image description here

Refer to this sample example for using X.509 certificate authentication in python.

Upvotes: 0

Related Questions