def test_lifetime(): global testCounter global device global eventRaised if config["TEST_ID"] == 2: keyORcert = config["cert"] else: keyORcert = compute_key(config["masterKey"], "dev1") device = iotc.Device(config["scopeId"], keyORcert, "dev1", config["TEST_ID"]) # 1 / 2 (symm / x509) if "modelData" in config: assert device.setModelData(config["modelData"]) == 0 device.setExitOnError(True) hostName = None def onconnect(info): global testCounter global eventRaised print "PASS = "******"ConnectionStatus", onconnect) == 0 # assert device.setLogLevel(IOTLogLevel.IOTC_LOGGING_ALL) == 0 assert device.setDPSEndpoint(config["hostName"]) == 0 assert device.connect() == 0 hostName = device.getHostName() showCommandWarning = False MAX_EXPECTED_TEST_COUNTER = 3 while testCounter < MAX_EXPECTED_TEST_COUNTER: if eventRaised == True: eventRaised = False if testCounter == 1: print "DISCONNECTS" assert device.disconnect() == 0 else: print "CONNECTS" device = iotc.Device(config["scopeId"], keyORcert, "dev1", config["TEST_ID"]) # 1 / 2 (symm / x509) assert device.on("ConnectionStatus", onconnect) == 0 # assert device.setLogLevel(IOTLogLevel.IOTC_LOGGING_ALL) == 0 assert device.setDPSEndpoint(config["hostName"]) == 0 device.connect(hostName) device.doNext() assert device.disconnect() == 0
def __init__(self): print('init_iotc') deviceId = os.getenv("DEVICE_ID") scopeId = os.getenv("SCOPE_ID") deviceKey = os.getenv("DEVICE_KEY") self.client = iotc.Device(scopeId, deviceKey, deviceId, IOTConnectType.IOTC_CONNECT_SYMM_KEY) self.client.setLogLevel(IOTLogLevel.IOTC_LOGGING_API_ONLY) self.simDeviceModel = SimDeviceModel()
def test_lifetime(id): deviceId = "dev" + str(id + 1) devices.append( iotc.Device(config["scopeId"], compute_key(config["masterKey"], deviceId), deviceId, config["TEST_ID"])) # 1 / 2 (symm / x509) if "modelData" in config: assert devices[id].setModelData(config["modelData"]) == 0 devices[id].setExitOnError(True) def onconnect(info): global testCounter if devices[id].isConnected(): assert info.getStatusCode() == 0 testCounter += 1 assert devices[id].sendTelemetry( "{\"temp\":22}", {"iothub-creation-time-utc": time.time()}) == 0 testCounter += 1 assert devices[id].sendProperty("{\"dieNumber\":3}") == 0 else: print("- ", "done", "device", deviceId) def onmessagesent(info): global testCounter print("onmessagesent", deviceId, info.getTag(), info.getPayload()) testCounter += 1 def oncommand(info): global testCounter print("oncommand", deviceId, info.getTag(), info.getPayload()) assert info.getTag() == "echo" testCounter += 1 allSettings = {} def onsettingsupdated(info): global testCounter testCounter += 1 assert '$version' in json.loads( info.getPayload()) # each setting has a version assert not info.getTag() + str(id) in allSettings # no double event allSettings[info.getTag() + str(id)] = True print("onsettingsupdated", deviceId, info.getTag(), info.getPayload()) assert devices[id].on("ConnectionStatus", onconnect) == 0 assert devices[id].on("MessageSent", onmessagesent) == 0 assert devices[id].on("Command", oncommand) == 0 assert devices[id].on("SettingsUpdated", onsettingsupdated) == 0 assert devices[id].setLogLevel(IOTLogLevel.IOTC_LOGGING_ALL) == 0 assert devices[id].setDPSEndpoint(config["hostName"]) == 0 assert devices[id].connect() == 0
def connect(self): self.conn = iotc.Device(self.scopeId, self.deviceKey, self.deviceId, IOTConnectType.IOTC_CONNECT_SYMM_KEY) self.conn.setLogLevel(IOTLogLevel.IOTC_LOGGING_API_ONLY) self.conn.setQosLevel(IOTQosLevel.IOTC_QOS_AT_MOST_ONCE) self.conn.on("ConnectionStatus", self.onconnect) self.conn.on("MessageSent", self.onmessagesent) self.conn.on("Command", self.oncommand) self.conn.connect()
def Connect(scope_id, device_id, key, callback): # create azure iot device instance device = iotc.Device(scope_id, key, device_id, IOTConnectType.IOTC_CONNECT_SYMM_KEY) device.setTokenExpiration(21600) # 6 hours device.setLogLevel(IOTLogLevel.IOTC_LOGGING_API_ONLY) # setup event callbacks device.on("ConnectionStatus", callback) device.on("MessageSent", callback) device.on("Command", callback) device.on("SettingsUpdated", callback) if device.connect() != 0: sys.exit(1) return device
def __init__(self, scope_id, app_key, device_id, model_data, logger): self.scope_id = scope_id self.app_key = app_key self.device_id = device_id self.logger = logger device_key = Device._compute_derived_symmetric_key( self.app_key, self.device_id) self.client = iotc.Device(self.scope_id, device_key, self.device_id, IOTConnectType.IOTC_CONNECT_SYMM_KEY) self.client.setLogLevel(IOTLogLevel.IOTC_LOGGING_API_ONLY) self.client.setModelData(model_data) # set callbacks self.client.on('ConnectionStatus', self._on_connect) self.client.on('MessageSent', self._on_message_sent) self.client.on('Command', self._on_command) self.client.on('SettingsUpdated', self._on_settings_updated)
humidity = humidity * (1.0 - dig_H1 * humidity / 524288.0) if humidity > 100: humidity = 100 elif humidity < 0: humidity = 0 return temperatureF / 100.0, pressure / 100.0, humidity ## End BME deviceId = "17f83c9b-e31c-4e11-8b9c-1b89ee99e714" scopeId = "0ne00062CC3" deviceKey = "V4sxmvey5dA5PBNqtCatp5uUZn/JwppsfIfZXdusocc=" iotc = iotc.Device(scopeId, deviceKey, deviceId, IOTConnectType.IOTC_CONNECT_SYMM_KEY) iotc.setLogLevel(IOTLogLevel.IOTC_LOGGING_API_ONLY) gCanSend = False gCounter = 0 def onconnect(info): global gCanSend print("- [onconnect] => status:" + str(info.getStatusCode())) if info.getStatusCode() == 0: if iotc.isConnected(): gCanSend = True def onmessagesent(info):
def test_lifetime(): global testCounter if config["TEST_ID"] == 2: keyORcert = config["cert"] else: keyORcert = compute_key(config["masterKey"], "dev1") device = iotc.Device(config["scopeId"], keyORcert, "dev1", config["TEST_ID"]) # 1 / 2 (symm / x509) if "modelData" in config: assert device.setModelData(config["modelData"]) == 0 device.setExitOnError(True) def onconnect(info): global testCounter if device.isConnected(): assert info.getStatusCode() == 0 testCounter += 1 assert device.sendTelemetry( "{\"temp\":22}", {"iothub-creation-time-utc": time.time()}) == 0 testCounter += 1 assert device.sendProperty("{\"dieNumber\":3}") == 0 else: print("- ", "done") def onmessagesent(info): global testCounter print("onmessagesent", info.getTag(), info.getPayload()) testCounter += 1 def oncommand(info): global testCounter print("oncommand", info.getTag(), info.getPayload()) assert info.getTag() == "echo" or info.getTag() == "countdown" testCounter += 1 allSettings = {} def onsettingsupdated(info): global testCounter testCounter += 1 assert '$version' in json.loads( info.getPayload()) # each setting has a version allSettings[info.getTag()] = True print("onsettingsupdated", info.getTag(), info.getPayload()) assert device.on("ConnectionStatus", onconnect) == 0 assert device.on("MessageSent", onmessagesent) == 0 assert device.on("Command", oncommand) == 0 assert device.on("SettingsUpdated", onsettingsupdated) == 0 assert device.setLogLevel(IOTLogLevel.IOTC_LOGGING_ALL) == 0 assert device.setDPSEndpoint(config["hostName"]) == 0 assert device.connect() == 0 showCommandWarning = False MAX_EXPECTED_TEST_COUNTER = 11 while device.isConnected() and testCounter < MAX_EXPECTED_TEST_COUNTER: if showCommandWarning == False and testCounter >= MAX_EXPECTED_TEST_COUNTER - 2: showCommandWarning = True print("now, send a command from central") device.doNext() assert device.disconnect() == 0
import io, iotc, json, logging, time from iotc import IOTConnectType, IOTLogLevel from datetime import datetime from random import randint import config as cfg mslog = logging.getLogger('msiotc_test') msfh = logging.FileHandler('msiotc_test.log') formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s') msfh.setFormatter(formatter) mslog.addHandler(msfh) mslog.setLevel(logging.DEBUG) iotc = iotc.Device(cfg.scopeId, cfg.deviceKey, cfg.deviceId, IOTConnectType.IOTC_CONNECT_SYMM_KEY) iotc.setLogLevel(IOTLogLevel.IOTC_LOGGING_API_ONLY) mslog.info('Profile: ' + str(cfg.profile)) gCanSend = False gCounter = 0 def onconnect(info): global gCanSend #print("- [onconnect] => status:" + str(info.getStatusCode())) mslog.info('[onconnect] => status: ' + str(info.getStatusCode())) if info.getStatusCode() == 0: if iotc.isConnected(): mslog.info('Connected')
# Copyright (c) Microsoft. All rights reserved. # Licensed under the MIT license. import iotc from iotc import IOTConnectType, IOTLogLevel from random import randint deviceId = "DEVICE_ID" scopeId = "SCOPE_ID" cert = { "certfile": "./subject-cert.pem", "keyfile": "./subject-private-key.pem", } iotc = iotc.Device(scopeId, cert, deviceId, IOTConnectType.IOTC_CONNECT_X509_CERT) iotc.setLogLevel(IOTLogLevel.IOTC_LOGGING_API_ONLY) gCanSend = False gCounter = 0 def onconnect(info): global gCanSend print("- [onconnect] => status:" + str(info.getStatusCode())) if info.getStatusCode() == 0: if iotc.isConnected(): gCanSend = True def onmessagesent(info):
t3max = 1 #Specify the cadence in which you would like to send values (seconds) seconds = 2 ############################# #IOT CENTRAL CONNECTION INFO# ############################# #Enter in your Credential Type, Certificate, Scope ID and Device ID from the IoT Central UI. credType = IOTConnectType.IOTC_CONNECT_SYMM_KEY keyORcert = "************************" scopeId = '*******' deviceId = '********' #Establish IoT Central Connection with those values device = iotc.Device(scopeId, keyORcert, deviceId, credType) device.connect() #Construct a JSON payload of telemetry and properties to send to IoTC at the specified cadence. #A UUID and timestamep are generated by default as part of the properties. def sendMessage(): telemetryvalues = { t1name: random.randint(t1min, t1max), t2name: random.randint(t2min, t2max), t3name: random.randint(t3min, t3max) } propertyvalues = { 'source': 'python-script', 'id': uuid.uuid4().hex, 'timestamp': str(datetime.datetime.utcnow())