Sample Code for TPM authorized SDK
This SDK will support TPM based authentication for azure iothub.
# | Date | Name | Download |
---|---|---|---|
1 | 12/18/2020 | TPM device Sample v2.1.2 ( preview ) | Download |
2 | 10/23/2020 | TPM device Sample v2.1.1 ( preview ) | Download |
3 | 08/14/2020 | TPM device Sample v2.1 ( preview ) | Download |
How to Run the Python sample code?
Prerequisite tools:
- Python: Python version 2.7.9, 3.5 and 3.6
- pip: pip is compatible to the python version. Use bellow command to install pip with setup tools
- pip install –upgrade -vv setuptools
- pip install ntplib (Required library for the SDK package)
Installation:
- Download and extract the file “iotconnect-sdk-python-v2.1.zip” (You can download SDK file from here).
- To install the required libraries, use the command given below:
-
- Goto SDK directory path using terminal/Command prompt
- cd iotconnect-sdk/
- pip install iotconnect-sdk-2.1.tar.gz (TPM 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>> scopeId = <<DPS scopeId>> // For TPM Authorized device only
To get the device information and connect to the device
For TPM Authorized device
with IoTConnectSDK(cpid, uniqueId, scopeId, 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)
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:
{ "maxSize": 5, // In MB size, Default = 10 MB "fileCount": 5 // Default = 1 }
- 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
""" after installing the IoTConnectSDK please run this sample. to run this sample you need env,uniqueId,cpId,sdkOptions env:- It is the environment that you have to pass at the initialization of SDK uniqueId:- which you get from IOthub/Iotconnect cpId:- which you get from IOthub/Iotconnect scopeId:-you will get from our team sdkOptions:- our SDK supports CA sign and offline data storage capability. """ # Compatible with python 2.* version import sys import json import time import threading import random from iotconnect import IoTConnectSDK from datetime import datetime #Get your "ENV" and "CPID" from the portal key vaults module or visit https://help.iotconnect.io SDK section. env = "<>" uniqueId = "<>" cpId = "<>" scopeId = "<>" interval = 10 # second.. delay tProcess = None dataArray = [] d2cMsg = None """ callbackMessage(msg) you will get your message and firmware update and other commands from iotconnect(cloud). """ 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": data = msg["data"] if msg["data"] != None else None if data != None: d2cMsg = { "ackId" : data['ackId'], "st" : 6, "msg" : "", "childId" : "" # if child than add childid } # Firmware Upgrade if cmdType == "0x02": data = msg["data"] if msg["data"] != None else None if data != None: d2cMsg = { "ackId" : data['ackId'], "st" : 7, "msg" : "", "childId" : "" # if child than add childid } """ callbackTwinMessage(msg) you will get twin property from here """ 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 """ before send data to make sure attributes are in your Iotconnect template. your sensors or attributes. in this sample we use Temperature and Gyroscope as attributes. """ def processData(): try: # Sample Data return { "Temperature": random.randint(10,50) } #return None except: return None def main(): global tProcess, dataArray, d2cMsg,env try: with IoTConnectSDK(cpId, uniqueId, scopeId, callbackMessage, callbackTwinMessage, env) as sdk: try: #sdk.GetAttributes() # # Note : cmdType = "0x02" - Firmware Upgrade # sdk.SendACK(d2cMsg,current_time,11) # Send acknowledgement # 11 : Firmware acknowledgement # e.g : acknowledgment data # { # "ackId" : data['ackId'], # "st" : 7, # "msg" : "" # "childId" : "" # } while True: dataArray = [] 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) == 1: tProcess = threading.Thread(target = sendBackToSDK, args = [sdk, dataArray]) tProcess.setName("SEND") tProcess.daemon = True tProcess.start() tProcess.join(1) # Send acknowledgement if d2cMsg != None: if d2cMsg["st"] == 7: current_time=datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%S.000Z") sdk.SendACK(d2cMsg,current_time,11) # 11 : Firmware acknowledgement elif d2cMsg["st"] == 6: current_time=datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%S.000Z") sdk.SendACK(d2cMsg,current_time,5) # 5 : command acknowledgement d2cMsg = None except KeyboardInterrupt: sys.exit(0) except Exception as ex: print(ex.message) sys.exit(0) if __name__ == "__main__": main()