Sample Code for Standard SDK
This SDK will support Symmetric Key and x509 Certificate based authentication for azure iothub.
# | Date | Name | Download |
---|---|---|---|
1 | 08/14/2020 | Symmetric Key Sample v2.0 | Download |
2 | 08/14/2020 | Symmetric Key Gateway Sample v2.0 | Download |
3 | 08/14/2020 | Self Sign Sample v2.0 | Download |
4 | 08/14/2020 | Self Sign Gateway Sample v2.0 | Download |
5 | 08/14/2020 | CA Sign Sample v2.0 | Download |
6 | 08/14/2020 | CA Sign Gateway Sample v2.0 | Download |
How to Run the Python sample code?
Prerequisite tools:
- Python: Python version 2.7.9 and above, 3.6 and 3.7
- pip: pip is compatible to the python version
Installation:
- Download and extract the file. (You can download SDK file from here)
- SDK version 2.0 : “iotconnect-sdk-python-v2.0.zip”
- SDK version 2.0.1 : “iotconnect-sdk-python-v2.0.1.zip”
- To install the required libraries, use the command given below:
-
- Goto SDK directory path using terminal/Command prompt
- cd iotconnect-sdk/
- SDK version 2.0 : pip install iotconnect-sdk-2.0.tar.gz (Symmetric key or SSL/x509 Authorized device)
- SDK version 2.0.1 : pip install iotconnect-sdk-2.0.1.tar.gz (Symmetric key or SSL/x509 Authorized device)
- Download Sample file from the above list and put on iotconnect-sdk/
- Run Your Sample code:
- python <<YOUR SAMPLE FILE>>.py
Public Methods and Implementation
Import library
from IoTConnectSDK import IoTConnectSDK
Prerequisite input data
uniqueId = <<uniqueId>> cpid = <<CPID>> env = <<env>>
To get the device information and connect to the device
For Standard Device Initialization
with IoTConnectSDK(cpid, uniqueId, callbackMessage, callbackTwinMessage, env) as sdk:
To receive the command from Cloud to Device(C2D)
def callbackMessage(msg): print(msg)
To receive the twin from Cloud to Device(C2D)
def callbackTwinMessage(msg): print(msg)
To get the list of attributes
sdk.GetAttributes()
To send the data from Device To Cloud(D2C)
sdk.SendData(sendTeledata)
To update the Twin Property
key = "firmware_version" value = "4.0" sdk.UpdateTwin(key, value)
SDK Configuration
- “properties.json” is required to give additional information regarding certificates and manage offline storage
- You can find “properties.json” in sample folder i.e. “sample/properties.json”, if SDK doesn’t find this file then it will give “Config file not found” error. Means you are missing this file at root location in case you are integrating with firmware
- Standard file format for the properties.json file is as below:
{ "certificate" : { "SSLKeyPath" : "<< file path >>/key.pem", "SSLCertPath" : "<< file path >>/cert.pem", "SSLCaPath" : "<< file path >>/ca.cert.pem" }, "maxSize": 5, // In MB size, Default = 10 MB "fileCount": 5 // Default = 1 }
- If your device is using certificate base authentication then you have to provide bellow information else you can keep it blank. Make sure each file path are valid and accessible:
- certificate.SSLKeyPath : Device key file path
- certificate.SSLCertPath: Device certificate file path
- certificate.SSLCaPath : Root server CA certificate file path
- If you want to store offline message then you can set bellow properties:
- maxSize : It allows us to configure the maximum file size limit(In MB).
- fileCount : It allows us to configure the maximum number of files that will be created for off-line data storage. It will store the data on the same location where you execute the code (Location: “logs/.txt”).
NOTE: It will cause an issue if property name got changed so please make sure none of the property get renamed. To avoid the file permission issue, start the script with the admin user.
Sample Code
# Compatible with python 2.* version import sys import json import time import threading import random from iotconnect import IoTConnectSDK from datetime import datetime env = "<< Environment >>" uniqueId = "<< Device UniqueID >>" cpId = "<< CPID >>" interval = 1 tProcess = None dataArray = [] d2cMsg = None def callbackMessage(msg): global d2cMsg print("\n--- Command Message Received ---") cmdType = None if msg != None and len(msg.items()) != 0: cmdType = msg["cmdType"] if msg["cmdType"] != None else None # Other Command if cmdType == "0x01": print(json.dumps(msg)) # Firmware Upgrade if cmdType == "0x02": data = msg["data"] if msg["data"] != None else None if data != None: print(json.dumps(data)) d2cMsg = { "guid" : data['guid'], "st" : 3, "msg" : "" } def callbackTwinMessage(msg): if msg: print("\n--- Twin Message Received ---") print(json.dumps(msg)) def sendBackToSDK(sdk, dataArray): global tProcess sdk.SendData(dataArray) time.sleep(interval) tProcess = None def processData(): try: # Sample Data return { "Temperature": random.randint(20,50), "Humidity": random.randint(10,50), "Gyroscope": { 'x': random.randint(1,10), 'y': random.randint(1,10), 'z': random.randint(1,10), } } #return None except: return None def main(): global tProcess, dataArray, d2cMsg try: with IoTConnectSDK(cpId, uniqueId, callbackMessage, callbackTwinMessage, env) as sdk: try: while True: data = processData() if data != None: dObj = { "uniqueId": uniqueId, "time": datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%S.000Z"), "data": data } dataArray.append(dObj) if tProcess == None and len(dataArray) > 0: tProcess = threading.Thread(target = sendBackToSDK, args = [sdk, dataArray]) tProcess.setName("SEND") tProcess.daemon = True tProcess.start() tProcess.join(1) if d2cMsg != None: sdk.SendACK(11, d2cMsg) # 11 : Firmware acknowledgement d2cMsg = None except KeyboardInterrupt: sys.exit(0) except Exception as ex: print(ex.message) sys.exit(0) if __name__ == "__main__": main()