0

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.

4
  • Have you tried using Custom CA or if using in a test env then disable SSL Verification but I feel the best approach is to use a custom CA bundle with the certifi library to ensure SSL verification is properly handled. Commented Jul 17, 2024 at 6:13
  • @sai are you using connection string to connect or certificate to connect to azure IoT Hub. Commented Jul 17, 2024 at 6:28
  • Im using service connection string. Commented Jul 17, 2024 at 6:44
  • hi @Arko if I use Custom CA then where I should give the path my path is D:/new/ca_file.perm if I add ca_cert argument from_connection_string function it says "TypeError: IoTHubRegistryManager.from_connection_string() got an unexpected keyword argument 'ca_cert' Commented Jul 17, 2024 at 7:14

1 Answer 1

0

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.

Sign up to request clarification or add additional context in comments.

6 Comments

Can I use port 443 here because my 8883 port is blocked. If I can where to add the parameter.
Have to tried my code with connection string with deviceid.
tried your code in my personal pc it is working but the "temp": "100" is placed under "$version": 2 not like yours. but in my organization laptop I'm getting SSL error
Glad to know it working in personal pc .
Use SSL certificate trust by Azure IoT Hub from this SO. refer link to ssl in pc
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.