class IoTHub:
    def __init__(self, iothub_name, owner_key, suffix='.azure-devices.net'):
        self.iothub_name = iothub_name
        self.owner_key = owner_key
        self.suffix = suffix
        self.owner_connection_string = 'HostName={0}{1};SharedAccessKeyName=iothubowner;SharedAccessKey={2}'.format(
            self.iothub_name, self.suffix, owner_key)
        self.registry_manager = IoTHubRegistryManager(
            self.owner_connection_string)
        self.device_twin = IoTHubDeviceTwin(self.owner_connection_string)
        self.__device_clients = {}

    def create_device(self, device_id, primary_key='', secondary_key=''):
        return self.registry_manager.create_device(
            device_id, primary_key, secondary_key,
            IoTHubRegistryManagerAuthMethod.SHARED_PRIVATE_KEY)

    def get_device_list(self):
        return self.registry_manager.get_device_list(
            1000)  # NOTE: this API is marked as deprecated,
        # but Python SDK doesn't seem to offer
        # an alternative yet (03/25/2018).

    def get_device_twin(self, device_id):
        return self.device_twin.get_twin(device_id)

    def update_twin(self, device_id, payload):
        return self.device_twin.update_twin(device_id, payload)
def iothub_registrymanager_sample_run():
    try:
        # RegistryManager
        iothub_registry_manager = IoTHubRegistryManager(CONNECTION_STRING)

        # CreateDevice
        primary_key = "aaabbbcccdddeeefffggghhhiiijjjkkklllmmmn3344"
        secondary_key = "111222333444555666777888999000aaabbbcccdddee"
        auth_method = IoTHubRegistryManagerAuthMethod.SHARED_PRIVATE_KEY
        print("auth_method", auth_method)
        new_device = iothub_registry_manager.create_device(
            DEVICE_ID, primary_key, secondary_key, auth_method)
        print(new_device)
        print_device_info("CreateDevice", new_device)

        # GetDevice
        iothub_device = iothub_registry_manager.get_device(DEVICE_ID)
        print_device_info("GetDevice", iothub_device)

        # UpdateDevice
        #primary_key = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
        #secondary_key = "yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy"
        #status = IoTHubDeviceStatus.DISABLED
        #auth_method = IoTHubRegistryManagerAuthMethod.SHARED_PRIVATE_KEY
        #iothub_registry_manager.update_device(DEVICE_ID, primary_key, secondary_key, status, auth_method)
        #updated_device = iothub_registry_manager.get_device(DEVICE_ID)
        #print_device_info("UpdateDevice", updated_device)

        # DeleteDevice
        #print ( "DeleteDevice" )
        #iothub_registry_manager.delete_device(DEVICE_ID)
        #print ( "" )

        # GetDeviceList
        print("GetDeviceList")
        #number_of_devices = 3
        dev_list = iothub_registry_manager.get_device_list(number_of_devices)

        number_of_devices = len(dev_list)
        print("Number of devices                        : {0}".format(
            number_of_devices))

        for device in range(0, number_of_devices):
            title = "Device " + str(device)
            print_device_info(title, dev_list[device])
        print("")

        # GetStatistics
        #iothub_registry_statistics = iothub_registry_manager.get_statistics()
        #print ( "GetStatistics" )
        #print ( "Total device count                       : {0}".format(iothub_registry_statistics.totalDeviceCount) )
        #print ( "Enabled device count                     : {0}".format(iothub_registry_statistics.enabledDeviceCount) )
        #print ( "Disabled device count                    : {0}".format(iothub_registry_statistics.disabledDeviceCount) )
        #print ( "" )

    except IoTHubError as iothub_error:
        print("Unexpected error {0}".format(iothub_error))
        return
    except KeyboardInterrupt:
        print("IoTHubRegistryManager sample stopped")
Esempio n. 3
0
 def __init__(self, iothub_name, owner_key, suffix='.azure-devices.net'):
     self.iothub_name = iothub_name
     self.owner_key = owner_key
     self.iothub_host = iothub_name + suffix
     self.owner_connection_string ='HostName={0};SharedAccessKeyName=iothubowner;SharedAccessKey={1}'.format(self.iothub_host, owner_key)
     self.registry_manager = IoTHubRegistryManager(self.owner_connection_string)
     self.device_twin = IoTHubDeviceTwin(self.owner_connection_string)
     self.__device_clients = {}
def iothub_registrymanager_sample_run():
    try:
        # RegistryManager
        iothub_registry_manager = IoTHubRegistryManager(CONNECTION_STRING)

        # CreateDevice
        primary_key = "aaabbbcccdddeeefffggghhhiiijjjkkklllmmmnnnoo"
        secondary_key = "111222333444555666777888999000aaabbbcccdddee"
        auth_method = IoTHubRegistryManagerAuthMethod.SHARED_PRIVATE_KEY
        new_device = iothub_registry_manager.create_device(DEVICE_ID, primary_key, secondary_key, auth_method)
        print_device_info("CreateDevice", new_device)

        # GetDevice
        iothub_device = iothub_registry_manager.get_device(DEVICE_ID)
        print_device_info("GetDevice", iothub_device)

        # UpdateDevice
        primary_key = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
        secondary_key = "yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy"
        status = IoTHubDeviceStatus.DISABLED
        auth_method = IoTHubRegistryManagerAuthMethod.SHARED_PRIVATE_KEY
        iothub_registry_manager.update_device(DEVICE_ID, primary_key, secondary_key, status, auth_method)
        updated_device = iothub_registry_manager.get_device(DEVICE_ID)
        print_device_info("UpdateDevice", updated_device)

        # DeleteDevice
        print ( "DeleteDevice" )
        iothub_registry_manager.delete_device(DEVICE_ID)
        print ( "" )

        # GetDeviceList
        print ( "GetDeviceList" )
        number_of_devices = 3
        dev_list = iothub_registry_manager.get_device_list(number_of_devices)

        number_of_devices = len(dev_list)
        print ( "Number of devices                        : {0}".format(number_of_devices) )

        for device in range(0, number_of_devices):
            title = "Device " + str(device)
            print_device_info(title, dev_list[device])
        print ( "" )

        # GetStatistics
        iothub_registry_statistics = iothub_registry_manager.get_statistics()
        print ( "GetStatistics" )
        print ( "Total device count                       : {0}".format(iothub_registry_statistics.totalDeviceCount) )
        print ( "Enabled device count                     : {0}".format(iothub_registry_statistics.enabledDeviceCount) )
        print ( "Disabled device count                    : {0}".format(iothub_registry_statistics.disabledDeviceCount) )
        print ( "" )

    except IoTHubError as iothub_error:
        print ( "Unexpected error {0}".format(iothub_error) )
        return
    except KeyboardInterrupt:
        print ( "IoTHubRegistryManager sample stopped" )
Esempio n. 5
0
def iothub_createdevice():
    try:
        iothub_registry_manager = IoTHubRegistryManager(CONNECTION_STRING)
        auth_method = IoTHubRegistryManagerAuthMethod.SHARED_PRIVATE_KEY
        new_device = iothub_registry_manager.create_device(DEVICE_ID, "", "", auth_method)
        print_device_info("CreateDevice", new_device)

    except IoTHubError as iothub_error:
        print("Unexpected error {0}".format(iothub_error))
        return
    except KeyboardInterrupt:
        print("iothub_createdevice stopped")
def get_device(device_id):
    try:
        print "hello"
        device_id = str(device_id)
        CONNECTION_STRING = "HostName=ttpliot.azure-devices.net;SharedAccessKeyName=iothubowner;SharedAccessKey=xBmNYVmuqN9sVZYQprYKvpv/2kv9GX1CdiSb5W+5KBc="
        iothub_registry_manager = IoTHubRegistryManager(CONNECTION_STRING)
        iothub_device = iothub_registry_manager.get_device(device_id)
        print "iothub_device.deviceId", iothub_device.deviceId
        return iothub_device.deviceId

    except IoTHubError as iothub_error:
        print("Unexpected error {0}".format(iothub_error))
        return None
def get_device_list(self):
    print("GetDeviceList")
    iothub_registry_manager = IoTHubRegistryManager(CONNECTION_STRING)
    iothub_registry_statistics = iothub_registry_manager.get_statistics()
    number_of_devices = iothub_registry_statistics.totalDeviceCount
    dev_list = iothub_registry_manager.get_device_list(number_of_devices)
    print dev_list
    number_of_devices = len(dev_list)
    print("Number of devices                        : {0}".format(
        number_of_devices))
    list1 = []
    for device in range(0, number_of_devices):
        list1.append(dev_list[device].deviceId)
    print list1
def iothub_registrymanager_modules_sample_run():
    try:
        # RegistryManager
        iothub_registry_manager = IoTHubRegistryManager(CONNECTION_STRING)

        # CreateModule
        primary_key = "aaabbbcccdddeeefffggghhhiiijjjkkklllmmmnnnoo"
        secondary_key = "111222333444555666777888999000aaabbbcccdddee"
        auth_method = IoTHubRegistryManagerAuthMethod.SHARED_PRIVATE_KEY
        new_module = iothub_registry_manager.create_module(DEVICE_ID, primary_key, secondary_key, MODULE_ID, auth_method)
        print_module_info("CreateModule", new_module)

        # GetModule
        iothub_module = iothub_registry_manager.get_module(DEVICE_ID, MODULE_ID)
        print_module_info("GetModule", iothub_module)

        # UpdateModule
        primary_key = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
        secondary_key = "yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy"
        auth_method = IoTHubRegistryManagerAuthMethod.SHARED_PRIVATE_KEY
        managedBy = "testManagedBy"
        iothub_registry_manager.update_module(DEVICE_ID, primary_key, secondary_key, MODULE_ID, auth_method, managedBy)
        updated_module = iothub_registry_manager.get_module(DEVICE_ID, MODULE_ID)
        print_module_info("UpdateModule", updated_module)

        # GetModuleList
        print ( "GetModuleList" )
        number_of_modules = 10
        modules_list = iothub_registry_manager.get_module_list(DEVICE_ID)

        number_of_modules = len(modules_list)
        print ( "Number of modules                        : {0}".format(number_of_modules) )

        for moduleIndex in range(0, number_of_modules):
            title = "Module " + str(moduleIndex)
            print_module_info(title, modules_list[moduleIndex])
        print ( "" )

        # DeleteModule
        print ( "DeleteModule" )
        iothub_registry_manager.delete_module(DEVICE_ID, MODULE_ID)
        print ( "" )

    except IoTHubError as iothub_error:
        print ( "Unexpected error {0}".format(iothub_error) )
        return
    except KeyboardInterrupt:
        print ( "IoTHubRegistryManager sample stopped" )
def iothub_create_device(DEVICE_ID, primary_key, secondary_key):
    try:
        print "i am here"
        CONNECTION_STRING = "HostName=ttpliot.azure-devices.net;SharedAccessKeyName=iothubowner;SharedAccessKey=xBmNYVmuqN9sVZYQprYKvpv/2kv9GX1CdiSb5W+5KBc="
        iothub_registry_manager = IoTHubRegistryManager(CONNECTION_STRING)
        auth_method = IoTHubRegistryManagerAuthMethod.SHARED_PRIVATE_KEY
        DEVICE_ID = str(DEVICE_ID)
        new_device = iothub_registry_manager.create_device(
            DEVICE_ID, primary_key, secondary_key, auth_method)

        device_info = "HostName=ttpliot.azure-devices.net" + ";" + str(
            new_device.deviceId) + ";" + str(primary_key)
        return device_info

    except IoTHubError as iothub_error:
        print("Unexpected error {0}".format(iothub_error))
        return
Esempio n. 10
0
def list_devices():
    print("GetDeviceList")
    number_of_devices = 3
    iothub_registry_manager = IoTHubRegistryManager(CONNECTION_STRING)
    dev_list = iothub_registry_manager.get_device_list(number_of_devices)

    number_of_devices = len(dev_list)
    print("Number of devices                        : {0}".format(
        number_of_devices))

    for device in range(0, number_of_devices):
        title = "Device " + str(device)
        print_device_info(title, dev_list[device])
        if dev_list[device].connectionState != "CONNECTED":
            DEVICE_STATUS = False
        #print(DEVICE_STATUS)
    print("")
Esempio n. 11
0
 def register_new(self, devices):
     
     for i in xrange(len(devices)): 
         
         #iothub_registry_manager = IoTHubRegistryManager(self.CONNECTION_STRING)
 
         try:
             ID = "::VD::"+devices[i].__str__()
             iothub_registry_manager = IoTHubRegistryManager(self.CONNECTION_STRING)
             auth_method = IoTHubRegistryManagerAuthMethod.SHARED_PRIVATE_KEY
             new_device = iothub_registry_manager.create_device(ID, "", "", auth_method)
     
             self.write_json_device(ID, new_device)
     
         except IoTHubError as iothub_error:
             print ( "Unexpected error {0}".format(iothub_error) )
             return
         except KeyboardInterrupt:
             print ( "iothub_createdevice stopped" )
Esempio n. 12
0
def iothub_createdevice():
    try:
        iothub_registry_manager = IoTHubRegistryManager(CONNECTION_STRING)
        auth_method = IoTHubRegistryManagerAuthMethod.SHARED_PRIVATE_KEY
        new_device = iothub_registry_manager.create_device(
            DEVICE_ID, "", "", auth_method)
        print_device_info("CreateDevice", new_device)
        connectionData[
            "device_connection_string"] = "HostName={0};DeviceId={1};SharedAccessKey={2}".format(
                connectionData["host_name"], new_device.deviceId,
                new_device.primaryKey)
        file = open('connectionData.json', 'w+')
        file.write(json.dumps(connectionData))
        file.close()

    except IoTHubError as iothub_error:
        print("Unexpected error {0}".format(iothub_error))
        return
    except KeyboardInterrupt:
        print("iothub_createdevice stopped")
Esempio n. 13
0
def create_new_device(d_id):

    with open('settings/TylersHub') as json_data_file:
        data = json.load(json_data_file)
        for field in data['iot_config']:
            CONNECTION_STRING = field['pk_connection_string'].__str__()

    iothub_registry_manager = IoTHubRegistryManager(CONNECTION_STRING)

    try:
        ID = "::VD::" + d_id.__str__()
        iothub_registry_manager = IoTHubRegistryManager(CONNECTION_STRING)
        auth_method = IoTHubRegistryManagerAuthMethod.SHARED_PRIVATE_KEY
        new_device = iothub_registry_manager.create_device(
            ID, "", "", auth_method)

        write_json_device(ID, new_device)

    except IoTHubError as iothub_error:
        print("Unexpected error {0}".format(iothub_error))
        return
    except KeyboardInterrupt:
        print("iothub_createdevice stopped")
Esempio n. 14
0
def iothub_createdevice():
    try:
    iothub_registry_manager = IoTHubRegistryManager(CONNECTION_STRING)
    auth_method = IoTHubRegistryManagerAuthMethod.SHARED_PRIVATE_KEY
    new_device = iothub_registry_manager.create_device(DEVICE_ID, "", "", auth_method)
    print_device_info("CreateDevice", new_device)

except IoTHubError as iothub_error:
    print ( "Unexpected error {0}".format(iothub_error) )
    return
except KeyboardInterrupt:
    print ( "iothub_createdevice stopped" )
    

if __name__ == '__main__':
    print ( "" )
    print ( "Python {0}".format(sys.version) )
    print ( "Creating device using the Azure IoT Hub Service SDK for Python" )
    print ( "" )
    print ( "    Connection string = {0}".format(CONNECTION_STRING) )
    print ( "    Device ID         = {0}".format(DEVICE_ID) )

    iothub_createdevice()
Esempio n. 15
0
def create_iothub_device(connection_string,
                         device_id="AgitareTechIoTWorkshopDevice"):
    """Creates device in Azure IoT Hub using the specified identifier

    :param: `connection_string` A connection string used to connect to IoT Hub

    :param: `device_id` The device identifier to use; defaults to _AgitareTechIoTWorkshopDevice_

    :type: `connection_string` str

    :type: `device_id` str
    """
    try:
        iothub_registry_manager = IoTHubRegistryManager(connection_string)
        auth_method = IoTHubRegistryManagerAuthMethod.SHARED_PRIVATE_KEY
        new_device = iothub_registry_manager.create_device(
            device_id, "", "", auth_method)
        print_device_info(new_device)

    except IoTHubError as iothub_error:
        print("Unexpected error {0}".format(iothub_error))
        return
    except KeyboardInterrupt:
        print("Creation of IoT Hub device stopped")
Esempio n. 16
0
def find_device(DEVICE_ID):

    with open('settings/devices.json') as json_data_file:
        data1 = json.load(json_data_file)
        #for field in data['registered_devices']:
        for i in xrange(len(data1['registered_devices'])):
            if data1['registered_devices'][i]['device_id'] == DEVICE_ID:
                print("FOUND DEVICE")
                with open('settings/iot.json') as json_data_file:
                    data2 = json.load(json_data_file)
                    for field in data2['iot_config']:
                        CONNECTION_STRING = field[
                            'pk_connection_string'].__str__()
                        iothub_registry_manager = IoTHubRegistryManager(
                            CONNECTION_STRING)
                        delete_device(iothub_registry_manager, DEVICE_ID)
                        return

            elif data1['registered_devices'][i]['device_id'] != DEVICE_ID and (
                    i + 1) == len(data1['registered_devices']):
                print("NO DEVICE FOUND")
Esempio n. 17
0
import sys, os
sys.path.append(os.getcwd())
from private import *

import iothub_service_client
from iothub_service_client import IoTHubRegistryManager, IoTHubRegistryManagerAuthMethod
from iothub_service_client import IoTHubDeviceStatus, IoTHubError, IoTHubRegistryManagerResult

iothub_registry_manager = IoTHubRegistryManager(CONNECTION_STRING)
auth_method = IoTHubRegistryManagerAuthMethod.SHARED_PRIVATE_KEY


def print_device_info(iothub_device):
    print("iothubDevice.deviceId                    = {0}".format(
        iothub_device.deviceId))
    print("iothubDevice.primaryKey                  = {0}".format(
        iothub_device.primaryKey))
    print("iothubDevice.secondaryKey                = {0}".format(
        iothub_device.secondaryKey))
    print("iothubDevice.connectionState             = {0}".format(
        iothub_device.connectionState))
    print("iothubDevice.status                      = {0}".format(
        iothub_device.status))
    print("iothubDevice.lastActivityTime            = {0}".format(
        iothub_device.lastActivityTime))
    print("iothubDevice.cloudToDeviceMessageCount   = {0}".format(
        iothub_device.cloudToDeviceMessageCount))
    print("iothubDevice.isManaged                   = {0}".format(
        iothub_device.isManaged))
    print("iothubDevice.authMethod                  = {0}".format(
        iothub_device.authMethod))
Esempio n. 18
0
def sc_create_registrymanager(iothub_connection_string):
    iothub_registry_manager = IoTHubRegistryManager(iothub_connection_string)
    assert iothub_registry_manager != None, "RegistryManager creation failed"
    return iothub_registry_manager
Esempio n. 19
0
def run_e2e_messaging(iothub_connection_string):
    global RECEIVE_CALLBACKS
    global MESSAGING_MESSAGE

    try:
        # prepare
        device_id = generate_device_name()
        assert isinstance(device_id, str), 'Invalid type returned!'

        primary_key = ""
        secondary_key = ""
        auth_method = IoTHubRegistryManagerAuthMethod.SHARED_PRIVATE_KEY

        iothub_registry_manager = IoTHubRegistryManager(
            iothub_connection_string)
        new_device = iothub_registry_manager.create_device(
            device_id, primary_key, secondary_key, auth_method)

        protocol = IoTHubTransportProvider.MQTT

        connection_string = get_connection_string(iothub_registry_manager,
                                                  IOTHUB_CONNECTION_STRING,
                                                  device_id, False)

        device_client = IoTHubClient(connection_string, protocol)
        assert isinstance(device_client,
                          IoTHubClient), 'Invalid type returned!'
        assert device_client != None, "device_client is NULL"

        device_client.set_option("messageTimeout", DEVICE_MESSAGE_TIMEOUT)

        device_client.set_message_callback(receive_message_callback,
                                           MESSAGING_CONTEXT)

        ###########################################################################
        # IoTHubMessaging

        # prepare
        # act
        iothub_messaging = IoTHubMessaging(IOTHUB_CONNECTION_STRING)

        # verify
        assert iothub_messaging != None, "iothub_messaging is NULL"
        ###########################################################################

        # Wait before open...
        sleep_before_device_action()

        ############################################################################
        # open

        # act
        iothub_messaging.open(open_complete_callback, None)
        ############################################################################

        ############################################################################
        # invoke

        # prepare
        MESSAGING_MESSAGE = ''.join(
            [random.choice(string.ascii_letters) for n in range(12)])
        message = IoTHubMessage(bytearray(MESSAGING_MESSAGE, 'utf8'))

        iothub_messaging.send_async(device_id, message, send_complete_callback,
                                    MESSAGING_CONTEXT)
        MESSAGE_RECEIVED_EVENT.wait(MESSAGE_RECEIVE_CALLBACK_TIMEOUT)

        # verify
        assert RECEIVE_CALLBACKS == 1, "message has not been received"
        ############################################################################

        print("")
        retval = 0
    except Exception as e:
        print("")
        print("run_e2e_messaging() failed with exception: {0}".format(e))
        retval = 1
    finally:
        # clean-up
        iothub_messaging.close()
        iothub_registry_manager.delete_device(device_id)

    return retval
Esempio n. 20
0
def run_e2e_method(iothub_connection_string, testing_modules):
    global DEVICE_METHOD_USER_CONTEXT
    global DEVICE_METHOD_NAME
    global DEVICE_METHOD_PAYLOAD
    global DEVICE_METHOD_TIMEOUT

    try:
        # prepare
        device_id = generate_device_name()
        assert isinstance(device_id, str), 'Invalid type returned!'

        primary_key = ""
        secondary_key = ""
        auth_method = IoTHubRegistryManagerAuthMethod.SHARED_PRIVATE_KEY

        iothub_registry_manager = IoTHubRegistryManager(
            iothub_connection_string)
        new_device = iothub_registry_manager.create_device(
            device_id, primary_key, secondary_key, auth_method)

        if testing_modules == True:
            new_module = iothub_registry_manager.create_module(
                device_id, primary_key, secondary_key, TEST_MODULE_ID,
                auth_method)
            protocol = IoTHubTransportProvider.AMQP
        else:
            protocol = IoTHubTransportProvider.MQTT

        connection_string = get_connection_string(iothub_registry_manager,
                                                  IOTHUB_CONNECTION_STRING,
                                                  device_id, testing_modules)

        device_client = IoTHubClient(connection_string, protocol)
        assert isinstance(device_client,
                          IoTHubClient), 'Invalid type returned!'
        assert device_client != None, "device_client is NULL"

        device_client.set_option("messageTimeout", DEVICE_MESSAGE_TIMEOUT)

        device_client.set_device_method_callback(device_method_callback,
                                                 DEVICE_METHOD_USER_CONTEXT)

        ###########################################################################
        # IoTHubDeviceMethod

        # prepare
        # act
        iothub_device_method = IoTHubDeviceMethod(IOTHUB_CONNECTION_STRING)

        # verify
        assert iothub_device_method != None, "iothub_device_method is NULL"
        ###########################################################################

        # Wait before invoke...
        sleep_before_device_action()

        ############################################################################
        # invoke

        # prepare
        # act
        if testing_modules == True:
            response = iothub_device_method.invoke(device_id, TEST_MODULE_ID,
                                                   DEVICE_METHOD_NAME,
                                                   DEVICE_METHOD_PAYLOAD,
                                                   DEVICE_METHOD_TIMEOUT)
        else:
            response = iothub_device_method.invoke(device_id,
                                                   DEVICE_METHOD_NAME,
                                                   DEVICE_METHOD_PAYLOAD,
                                                   DEVICE_METHOD_TIMEOUT)

        assert response != None, "response is NULL"
        assert isinstance(response,
                          IoTHubDeviceMethodResponse), 'Invalid type returned!'

        # verify
        response_ok = response.payload.find(DEVICE_CLIENT_RESPONSE)
        assert response_ok > 0, "response does not contain " + DEVICE_CLIENT_RESPONSE
        assert response.status == 200, "response status is : " + response.status
        DEVICE_METHOD_EVENT.wait(DEVICE_METHOD_CALLBACK_TIMEOUT)
        assert DEVICE_CLIENT_RESPONSE.find(
            DEVICE_METHOD_RESPONSE_PREFIX
        ) >= 0, "Timeout expired and device method has not been called!"
        ############################################################################

        print("")
        retval = 0
    except Exception as e:
        print("")
        print("run_e2e_method() failed with exception: {0}".format(e))
        retval = 1
    finally:
        # clean-up
        iothub_registry_manager.delete_device(device_id)

    return retval
Esempio n. 21
0
def run_e2e_twin(iothub_connection_string, testing_modules):
    try:
        # prepare
        device_id = generate_device_name()
        assert isinstance(device_id, str), 'Invalid type returned!'

        primary_key = ""
        secondary_key = ""
        auth_method = IoTHubRegistryManagerAuthMethod.SHARED_PRIVATE_KEY

        iothub_registry_manager = IoTHubRegistryManager(
            iothub_connection_string)
        new_device = iothub_registry_manager.create_device(
            device_id, primary_key, secondary_key, auth_method)

        if testing_modules == True:
            new_module = iothub_registry_manager.create_module(
                device_id, primary_key, secondary_key, TEST_MODULE_ID,
                auth_method)

        ###########################################################################
        # IoTHubDeviceTwin

        # act
        iothub_device_twin = IoTHubDeviceTwin(IOTHUB_CONNECTION_STRING)

        # verify
        assert iothub_device_twin != None, "iothub_device_twin is NULL"
        ###########################################################################

        ###########################################################################

        # Wait before get twin...
        sleep_before_device_action()

        ###########################################################################
        # get_twin

        # act
        if testing_modules == True:
            twin_info = iothub_device_twin.get_twin(device_id, TEST_MODULE_ID)
        else:
            twin_info = iothub_device_twin.get_twin(device_id)

        # verify
        assert twin_info != None, "twin_info is NULL"
        json_ok = twin_info.find("deviceId")
        assert json_ok > 0, "twin_info does not contain deviceId tag"
        json_ok = twin_info.find(device_id)
        assert json_ok > 0, "twin_info does not contain the correct device id"

        if testing_modules == True:
            json_ok = twin_info.find("moduleId")
            assert json_ok > 0, "twin_info does not contain moduleId tag"

        json_ok = twin_info.find("etag")
        assert json_ok > 0, "twin_info does not contain etag tag"
        json_ok = twin_info.find("properties")
        assert json_ok > 0, "twin_info does not contain properties tag"
        ###########################################################################

        print("")
        print("Twin before update:")
        print("{0}".format(twin_info))

        ###########################################################################
        # update_twin

        # prepare
        new_property_name = "telemetryInterval"
        new_property_value = "42"
        UPDATE_JSON = "{\"properties\":{\"desired\":{\"" + new_property_name + "\":" + new_property_value + "}}}"

        # act
        if testing_modules == True:
            twin_info = iothub_device_twin.update_twin(device_id,
                                                       TEST_MODULE_ID,
                                                       UPDATE_JSON)
        else:
            twin_info = iothub_device_twin.update_twin(device_id, UPDATE_JSON)

        # verify
        assert twin_info != None, "twin_info is NULL"
        json_ok = twin_info.find("deviceId")
        assert json_ok > 0, "twin_info does not contain deviceId tag"
        json_ok = twin_info.find(device_id)
        assert json_ok > 0, "twin_info does not contain the correct device id"

        json_ok = twin_info.find("etag")
        assert json_ok > 0, "twin_info does not contain etag tag"
        json_ok = twin_info.find("properties")
        assert json_ok > 0, "twin_info does not contain properties tag"

        json_ok = twin_info.find(new_property_name)
        assert json_ok > 0, "twin_info does not contain " + new_property_name + " tag"
        json_ok = twin_info.find(new_property_value)
        assert json_ok > 0, "twin_info does not contain " + new_property_value
        ###########################################################################

        print("")
        print("Device Twin after update:")
        print("{0}".format(twin_info))
        print("")
        retval = 0
    except Exception as e:
        print("")
        print("run_e2e_twin() failed with exception: {0}".format(e))
        retval = 1
    finally:
        # clean-up
        if testing_modules == True:
            iothub_registry_manager.delete_module(device_id, TEST_MODULE_ID)

        iothub_registry_manager.delete_device(device_id)

    return retval
Esempio n. 22
0
def run_e2e_registrymanager(iothub_connection_string):
    try:
        # prepare
        device_id = generate_device_name()
        assert isinstance(device_id, str), 'Invalid type returned!'

        ###########################################################################
        # IoTHubRegistryManager

        # prepare
        # act
        iothub_registry_manager = IoTHubRegistryManager(
            iothub_connection_string)

        # verify
        assert isinstance(iothub_registry_manager,
                          IoTHubRegistryManager), 'Invalid type returned!'
        assert iothub_registry_manager != None, "iothub_registry_manager is NULL"
        ###########################################################################

        print("IoTHubRegistryManager is created successfully")

        ###########################################################################
        # create_device

        # prepare
        primary_key = ""
        secondary_key = ""
        auth_method = IoTHubRegistryManagerAuthMethod.SHARED_PRIVATE_KEY

        # act
        new_device = iothub_registry_manager.create_device(
            device_id, primary_key, secondary_key, auth_method)

        # verify
        assert isinstance(new_device, IoTHubDevice), 'Invalid type returned!'
        assert new_device != None, "new_device is NULL"
        assert new_device.primaryKey != None, "new_device.primaryKey is NULL"
        assert new_device.primaryKey != "", "new_device.primaryKey is empty"
        assert new_device.secondaryKey != None, "new_device.secondaryKey is NULL"
        assert new_device.secondaryKey != "", "new_device.secondaryKey is empty"
        ###########################################################################

        print_device_or_module_info("CreateDevice", new_device, False)

        ###########################################################################
        # create_module_device

        # prepare
        primary_key = ""
        secondary_key = ""
        auth_method = IoTHubRegistryManagerAuthMethod.SHARED_PRIVATE_KEY

        # act
        new_module = iothub_registry_manager.create_module(
            device_id, primary_key, secondary_key, TEST_MODULE_ID, auth_method)

        # verify
        assert isinstance(new_module, IoTHubModule), 'Invalid type returned!'
        assert new_module != None, "new_module is NULL"
        assert new_module.primaryKey != None, "new_module.primaryKey is NULL"
        assert new_module.primaryKey != "", "new_module.primaryKey is empty"
        assert new_module.secondaryKey != None, "new_module.secondaryKey is NULL"
        assert new_module.secondaryKey != "", "new_module.secondaryKey is empty"
        ###########################################################################

        print_device_or_module_info("CreateModule", new_module, True)

        ###########################################################################
        # get_device
        get_device_info_and_verify("GetDevice", iothub_registry_manager,
                                   device_id)

        ###########################################################################
        # get_module
        get_module_info_and_verify("GetModule", iothub_registry_manager,
                                   device_id)

        ###########################################################################
        # update_device

        # prepare
        primary_key = ''.join([
            random.choice(string.ascii_letters + string.digits)
            for n in range(44)
        ])
        secondary_key = ''.join([
            random.choice(string.ascii_letters + string.digits)
            for n in range(44)
        ])
        status = IoTHubDeviceStatus.DISABLED
        auth_method = IoTHubRegistryManagerAuthMethod.SHARED_PRIVATE_KEY

        # act
        iothub_registry_manager.update_device(device_id, primary_key,
                                              secondary_key, status,
                                              auth_method)

        # verify
        get_device_info_and_verify("UpdateDevice", iothub_registry_manager,
                                   device_id)

        ###########################################################################
        # update_module

        # prepare
        primary_key = ''.join([
            random.choice(string.ascii_letters + string.digits)
            for n in range(44)
        ])
        secondary_key = ''.join([
            random.choice(string.ascii_letters + string.digits)
            for n in range(44)
        ])
        status = IoTHubDeviceStatus.DISABLED
        auth_method = IoTHubRegistryManagerAuthMethod.SHARED_PRIVATE_KEY

        # act
        iothub_registry_manager.update_module(device_id, primary_key,
                                              secondary_key, TEST_MODULE_ID,
                                              auth_method)

        # verify
        get_module_info_and_verify("UpdateModule", iothub_registry_manager,
                                   device_id)

        ###########################################################################
        # get_device_list

        # prepare
        req_number_of_devices = 10

        # act
        device_list = iothub_registry_manager.get_device_list(
            req_number_of_devices)

        # verify
        assert device_list != None, "device_list is NULL"
        number_of_devices = len(device_list)
        assert number_of_devices != None, "device_list is NULL"
        assert number_of_devices > 0, "number_of_devices is incorrect"
        ###########################################################################

        print("Number of devices                        : {0}".format(
            number_of_devices))

        ###########################################################################
        # get_statistics

        # prepare
        # act
        iothub_registry_statistics = iothub_registry_manager.get_statistics()

        # verify
        assert iothub_registry_statistics.totalDeviceCount >= 0, "iothub_registry_statistics.totalDeviceCount is incorrect"
        sum_device_count = iothub_registry_statistics.enabledDeviceCount + iothub_registry_statistics.disabledDeviceCount
        assert sum_device_count >= 0, "iothub_registry_statistics.totalDeviceCount is incorrect"
        ###########################################################################

        print("GetStatistics")
        print("Total device count                       : {0}".format(
            iothub_registry_statistics.totalDeviceCount))
        print("Enabled device count                     : {0}".format(
            iothub_registry_statistics.enabledDeviceCount))
        print("Disabled device count                    : {0}".format(
            iothub_registry_statistics.disabledDeviceCount))

        retval = 0
    except Exception as e:
        print("")
        print("run_e2e_registrymanager() failed with exception: {0}".format(e))
        retval = 1
    finally:
        ###########################################################################
        # delete_module
        # prepare
        # act
        iothub_registry_manager.delete_module(device_id, TEST_MODULE_ID)
        # verify

        ###########################################################################
        # delete_device

        # prepare
        # act
        iothub_registry_manager.delete_device(device_id)
        # verify
        ###########################################################################

    return retval
Esempio n. 23
0
class IoTHub:
    def __init__(self, iothub_name, owner_key, suffix='.azure-devices.net'):
        self.iothub_name = iothub_name
        self.owner_key = owner_key
        self.iothub_host = iothub_name + suffix
        self.owner_connection_string = 'HostName={0};SharedAccessKeyName=iothubowner;SharedAccessKey={1}'.format(
            self.iothub_host, owner_key)
        self.registry_manager = IoTHubRegistryManager(
            self.owner_connection_string)
        self.device_twin = IoTHubDeviceTwin(self.owner_connection_string)
        self.__device_clients = {}

    def create_device(self, device_id, primary_key='', secondary_key=''):
        return self.registry_manager.create_device(
            device_id, primary_key, secondary_key,
            IoTHubRegistryManagerAuthMethod.SHARED_PRIVATE_KEY)

    def get_device_list(self):
        return self.registry_manager.get_device_list(
            1000)  # NOTE: this API is marked as deprecated,
        # but Python SDK doesn't seem to offer
        # an alternative yet (03/25/2018).

    def get_device_twin(self, device_id):
        return self.device_twin.get_twin(device_id)

    def __get_sas_token(self, device_id, key, policy, expiry=3600):
        ttl = time() + expiry
        uri = '{0}/devices/{1}'.format(self.iothub_host, device_id)
        sign_key = "%s\n%d" % ((quote_plus(uri)), int(ttl))

        signature = b64encode(
            HMAC(b64decode(key), sign_key.encode('utf-8'), sha256).digest())

        rawtoken = {'sr': uri, 'sig': signature, 'se': str(int(ttl))}

        rawtoken['skn'] = policy

        sas = 'SharedAccessSignature ' + urlencode(rawtoken)
        return sas
        # return 'HostName={0}{1};DeviceId={2};SharedAccessSignature={3}'.format(self.iothub_name, self.suffix, device_id, sas)

    def update_twin(self, device_id, payload, etag='*'):
        """
            Update device twin.
            Unfortunately, Python IoTHub SDK does not implement optimistic concurrency, so
            falling back to the REST API.

            SDK equivalent:
            return self.device_twin.update_twin(device_id, payload)
        """
        twin_url = 'https://{0}/twins/{1}?api-version=2017-06-30'.format(
            self.iothub_host, device_id)
        sas_token = self.__get_sas_token(device_id, self.owner_key,
                                         'iothubowner')
        headers = {
            'Authorization': sas_token,
            'Content-Type': 'application/json',
            'If-Match': '"{0}"'.format(etag)
        }

        payload_json = json.loads(payload)

        keys = map(str.lower, payload_json.keys())

        if 'tags' not in keys:
            payload_json['tags'] = {}

        if 'desiredproperties' not in keys:
            payload_json['desiredProperties'] = {}

        payload = json.dumps(payload_json)

        r = requests.patch(twin_url, data=payload, headers=headers)
        assert r.status_code == HTTPStatus.OK

        return r.text

    def claim_device(self, client_id):
        while True:
            claimed_device = self.try_claim_device(client_id)
            if claimed_device:
                return claimed_device
            sleep(5)

    def try_claim_device(self, client_id):
        try:
            devices = self.get_device_list()
        except:
            return

        random.shuffle(devices)
        for device in devices:
            if device.connectionState == IoTHubDeviceConnectionState.CONNECTED:
                continue

            if device.status == IoTHubDeviceStatus.DISABLED:
                continue

            # attempt to acquire lock using device twin's optimistic concurrency
            twin_data = self.get_device_twin(device.deviceId)
            twin_data_json = json.loads(twin_data)
            etag = twin_data_json['etag']

            twin_tags = None
            if 'tags' not in twin_data_json:
                twin_tags = {}
            else:
                twin_tags = twin_data_json['tags']

            if 'simulated' not in twin_tags or not twin_tags['simulated']:
                continue

            if 'simulator' not in twin_tags:
                continue

            current_time = datetime.datetime.now().replace(tzinfo=None)

            if '_claim' in twin_tags:
                simulator_data = twin_tags['_claim']
                if 'lastClaimed' in simulator_data:
                    last_claimed = dateutil.parser.parse(
                        simulator_data['lastClaimed']).replace(tzinfo=None)
                    if (current_time - last_claimed).total_seconds() < 30:
                        continue

            twin_tags['_claim'] = {
                'clientId': client_id,
                'lastClaimed': current_time.isoformat()
            }

            updated_properties = {'tags': twin_tags}

            try:
                updated_twin_data = self.update_twin(
                    device.deviceId, json.dumps(updated_properties), etag)
                return device, updated_twin_data
            except:
                continue
def run_e2e_messaging(iothub_connection_string):
    global RECEIVE_CALLBACKS
    global MESSAGING_MESSAGE

    try:
        # prepare
        device_id = generate_device_name()
        assert isinstance(device_id, str), 'Invalid type returned!'

        primary_key = ""
        secondary_key = ""
        auth_method = IoTHubRegistryManagerAuthMethod.SHARED_PRIVATE_KEY

        iothub_registry_manager = IoTHubRegistryManager(iothub_connection_string)
        new_device = iothub_registry_manager.create_device(device_id, primary_key, secondary_key, auth_method)

        device_connection_string = get_device_connection_string(iothub_registry_manager, IOTHUB_CONNECTION_STRING, device_id)

        device_client = IoTHubClient(device_connection_string, IoTHubTransportProvider.MQTT)
        assert isinstance(device_client, IoTHubClient), 'Invalid type returned!'
        assert device_client != None, "device_client is NULL"

        device_client.set_option("messageTimeout", DEVICE_MESSAGE_TIMEOUT)

        device_client.set_message_callback(receive_message_callback, MESSAGING_CONTEXT)

        ###########################################################################
        # IoTHubMessaging

        # prepare
        # act
        iothub_messaging = IoTHubMessaging(IOTHUB_CONNECTION_STRING)

        # verify
        assert iothub_messaging != None, "iothub_messaging is NULL"
        ###########################################################################

        # Wait before open...
        time.sleep(SLEEP_BEFORE_DEVICE_ACTION)

        ############################################################################
        # open

        # act
        iothub_messaging.open(open_complete_callback, None)
        ############################################################################

        ############################################################################
        # invoke

        # prepare
        MESSAGING_MESSAGE = ''.join([random.choice(string.ascii_letters) for n in range(12)])
        message = IoTHubMessage(bytearray(MESSAGING_MESSAGE, 'utf8'))

        # act
        iothub_messaging.send_async(device_id, message, send_complete_callback, MESSAGING_CONTEXT)
        MESSAGE_RECEIVED_EVENT.wait(MESSAGE_RECEIVE_CALLBACK_TIMEOUT)

        # verify
        assert RECEIVE_CALLBACKS == 1, "message has not been received"
        ############################################################################

        print ( "" )
        retval = 0
    except Exception as e:
        print ( "" )
        print ("run_e2e_messaging() failed with exception: {0}".format(e))
        retval = 1
    finally:
        # clean-up
        iothub_messaging.close()
        iothub_registry_manager.delete_device(device_id)
    
    return retval
def run_e2e_devicemethod(iothub_connection_string):
    global DEVICE_METHOD_USER_CONTEXT
    global DEVICE_METHOD_NAME
    global DEVICE_METHOD_PAYLOAD
    global DEVICE_METHOD_TIMEOUT

    try:
        # prepare
        device_id = generate_device_name()
        assert isinstance(device_id, str), 'Invalid type returned!'

        primary_key = ""
        secondary_key = ""
        auth_method = IoTHubRegistryManagerAuthMethod.SHARED_PRIVATE_KEY

        iothub_registry_manager = IoTHubRegistryManager(iothub_connection_string)
        new_device = iothub_registry_manager.create_device(device_id, primary_key, secondary_key, auth_method)

        device_connection_string = get_device_connection_string(iothub_registry_manager, IOTHUB_CONNECTION_STRING, device_id)


        device_client = IoTHubClient(device_connection_string, IoTHubTransportProvider.MQTT)
        assert isinstance(device_client, IoTHubClient), 'Invalid type returned!'
        assert device_client != None, "device_client is NULL"

        device_client.set_option("messageTimeout", DEVICE_MESSAGE_TIMEOUT)

        device_client.set_device_method_callback(device_method_callback, DEVICE_METHOD_USER_CONTEXT)

        ###########################################################################
        # IoTHubDeviceMethod

        # prepare
        # act
        iothub_device_method = IoTHubDeviceMethod(IOTHUB_CONNECTION_STRING)

        # verify
        assert iothub_device_method != None, "iothub_device_method is NULL"
        ###########################################################################

        # Wait before invoke...
        time.sleep(SLEEP_BEFORE_DEVICE_ACTION)

        ############################################################################
        # invoke
        
        # prepare
        # act
        response = iothub_device_method.invoke(device_id, DEVICE_METHOD_NAME, DEVICE_METHOD_PAYLOAD, DEVICE_METHOD_TIMEOUT)
        assert response != None, "response is NULL"
        assert isinstance(response, IoTHubDeviceMethodResponse), 'Invalid type returned!'

        # verify
        response_ok = response.payload.find(DEVICE_CLIENT_RESPONSE)
        assert response_ok > 0, "response does not contain " + DEVICE_CLIENT_RESPONSE
        assert response.status == 200, "response status is : " + response.status
        DEVICE_METHOD_EVENT.wait(DEVICE_METHOD_CALLBACK_TIMEOUT)
        assert DEVICE_CLIENT_RESPONSE.find(DEVICE_METHOD_RESPONSE_PREFIX) >= 0, "Timeout expired and device method has not been called!"
        ############################################################################

        print ( "" )
        retval = 0
    except Exception as e:
        print ( "" )
        print ("run_e2e_devicemethod() failed with exception: {0}".format(e))
        retval = 1
    finally:
        # clean-up
        iothub_registry_manager.delete_device(device_id)

    return retval
def run_e2e_devicetwin(iothub_connection_string):
    try:
        # prepare
        device_id = generate_device_name()
        assert isinstance(device_id, str), 'Invalid type returned!'

        primary_key = ""
        secondary_key = ""
        auth_method = IoTHubRegistryManagerAuthMethod.SHARED_PRIVATE_KEY

        iothub_registry_manager = IoTHubRegistryManager(iothub_connection_string)
        new_device = iothub_registry_manager.create_device(device_id, primary_key, secondary_key, auth_method)

        ###########################################################################
        # IoTHubDeviceTwin

        # act
        iothub_device_twin = IoTHubDeviceTwin(IOTHUB_CONNECTION_STRING)

        # verify
        assert iothub_device_twin != None, "iothub_device_twin is NULL"
        ###########################################################################

        ###########################################################################

        # Wait before get twin...
        time.sleep(SLEEP_BEFORE_DEVICE_ACTION)

        ###########################################################################
        # get_twin

        # act
        twin_info = iothub_device_twin.get_twin(device_id)

        # verify
        assert twin_info != None, "twin_info is NULL"
        json_ok = twin_info.find("deviceId")
        assert json_ok > 0, "twin_info does not contain deviceId tag"
        json_ok = twin_info.find(device_id)
        assert json_ok > 0, "twin_info does not contain the correct device id"

        json_ok = twin_info.find("etag")
        assert json_ok > 0, "twin_info does not contain etag tag"
        json_ok = twin_info.find("properties")
        assert json_ok > 0, "twin_info does not contain properties tag"
        ###########################################################################

        print ( "" )
        print ( "Device Twin before update:" )
        print ( "{0}".format(twin_info) )

        ###########################################################################
        # update_twin

        # prepare
        new_property_name = "telemetryInterval"
        new_property_value = "42"
        UPDATE_JSON = "{\"properties\":{\"desired\":{\"" + new_property_name + "\":" + new_property_value + "}}}"

        # act
        twin_info = iothub_device_twin.update_twin(device_id, UPDATE_JSON)

        # verify
        assert twin_info != None, "twin_info is NULL"
        json_ok = twin_info.find("deviceId")
        assert json_ok > 0, "twin_info does not contain deviceId tag"
        json_ok = twin_info.find(device_id)
        assert json_ok > 0, "twin_info does not contain the correct device id"

        json_ok = twin_info.find("etag")
        assert json_ok > 0, "twin_info does not contain etag tag"
        json_ok = twin_info.find("properties")
        assert json_ok > 0, "twin_info does not contain properties tag"

        json_ok = twin_info.find(new_property_name)
        assert json_ok > 0, "twin_info does not contain " + new_property_name + " tag"
        json_ok = twin_info.find(new_property_value)
        assert json_ok > 0, "twin_info does not contain " + new_property_value
        ###########################################################################

        print ( "" )
        print ( "Device Twin after update:" )
        print ( "{0}".format(twin_info) )
        print ( "" )
        retval = 0
    except Exception as e:
        print ( "" )
        print ("run_e2e_devicetwin() failed with exception: {0}".format(e))
        retval = 1
    finally:
        # clean-up
        iothub_registry_manager.delete_device(device_id)

    return retval
def run_e2e_registrymanager(iothub_connection_string):
    try:
        # prepare
        device_id = generate_device_name()
        assert isinstance(device_id, str), 'Invalid type returned!'

        ###########################################################################
        # IoTHubRegistryManager
    
        # prepare
        # act
        iothub_registry_manager = IoTHubRegistryManager(iothub_connection_string)

        # verify
        assert isinstance(iothub_registry_manager, IoTHubRegistryManager), 'Invalid type returned!'
        assert iothub_registry_manager != None, "iothub_registry_manager is NULL"
        ###########################################################################

        print ( "IoTHubRegistryManager is created successfully" )

        ###########################################################################
        # create_device

        # prepare
        primary_key = ""
        secondary_key = ""
        auth_method = IoTHubRegistryManagerAuthMethod.SHARED_PRIVATE_KEY

        # act
        new_device = iothub_registry_manager.create_device(device_id, primary_key, secondary_key, auth_method)

        # verify
        assert isinstance(new_device, IoTHubDevice), 'Invalid type returned!'
        assert new_device != None, "new_device is NULL"
        assert new_device.primaryKey != None, "new_device.primaryKey is NULL"
        assert new_device.primaryKey != "", "new_device.primaryKey is empty"
        assert new_device.secondaryKey != None, "new_device.secondaryKey is NULL"
        assert new_device.secondaryKey != "", "new_device.secondaryKey is empty"
        ###########################################################################

        print_device_info("CreateDevice", new_device)

        ###########################################################################
        # get_device

        # prepare
        # act
        iothub_device = iothub_registry_manager.get_device(device_id)
  
        # verify
        assert isinstance(iothub_device, IoTHubDevice), 'Invalid type returned!'
        assert iothub_device != None, "iothub_device is NULL"
        assert iothub_device.primaryKey != None, "iothub_device.primaryKey is NULL"
        assert iothub_device.primaryKey != "", "iothub_device.primaryKey is empty"
        assert iothub_device.secondaryKey != None, "iothub_device.secondaryKey is NULL"
        assert iothub_device.secondaryKey != "", "iothub_device.secondaryKey is empty"
        ###########################################################################

        print_device_info("GetDevice", iothub_device)

        ###########################################################################
        # update_device

        # prepare
        primary_key = ''.join([random.choice(string.ascii_letters + string.digits) for n in range(44)])
        secondary_key = ''.join([random.choice(string.ascii_letters + string.digits) for n in range(44)])
        status = IoTHubDeviceStatus.DISABLED
        auth_method = IoTHubRegistryManagerAuthMethod.SHARED_PRIVATE_KEY

        # act
        iothub_registry_manager.update_device(device_id, primary_key, secondary_key, status, auth_method)
        updated_device = iothub_registry_manager.get_device(device_id)
    
        # verify
        assert isinstance(updated_device, IoTHubDevice), 'Invalid type returned!'
        assert updated_device != None, "updated_device is NULL"
        assert updated_device.primaryKey == primary_key, "updated_device.primaryKey is not updated"
        assert updated_device.secondaryKey == secondary_key, "updated_device.secondaryKey is not updated"
        assert updated_device.authMethod == auth_method, "updated_device.authMethod is not updated"
        assert updated_device.status == status, "updated_device.status is not updated"
        ###########################################################################

        print_device_info("UpdateDevice", updated_device)

        ###########################################################################
        # get_device_list

        # prepare
        req_number_of_devices = 10

        # act
        device_list = iothub_registry_manager.get_device_list(req_number_of_devices)

        # verify
        assert device_list != None, "device_list is NULL"
        number_of_devices = len(device_list)
        assert number_of_devices != None, "device_list is NULL"
        assert number_of_devices > 0, "number_of_devices is incorrect"
        ###########################################################################

        print ( "Number of devices                        : {0}".format(number_of_devices) )

        ###########################################################################
        # get_statistics
    
        # prepare
        # act
        iothub_registry_statistics = iothub_registry_manager.get_statistics()

        # verify
        assert iothub_registry_statistics.totalDeviceCount >= 0, "iothub_registry_statistics.totalDeviceCount is incorrect"
        sum_device_count = iothub_registry_statistics.enabledDeviceCount + iothub_registry_statistics.disabledDeviceCount
        assert sum_device_count >= 0, "iothub_registry_statistics.totalDeviceCount is incorrect"
        ###########################################################################

        print ( "GetStatistics" )
        print ( "Total device count                       : {0}".format(iothub_registry_statistics.totalDeviceCount) )
        print ( "Enabled device count                     : {0}".format(iothub_registry_statistics.enabledDeviceCount) )
        print ( "Disabled device count                    : {0}".format(iothub_registry_statistics.disabledDeviceCount) )
    
        retval = 0
    except Exception as e:
        print ( "" )
        print ("run_e2e_devicetwin() failed with exception: {0}".format(e))
        retval = 1
    finally:
        ###########################################################################
        # delete_device
 
        # prepare
        # act
        iothub_registry_manager.delete_device(device_id)
        # verify
        ###########################################################################

    return retval