Пример #1
0
class HubManager(object):

    def __init__(
            self,
            connection_string):
        self.client_protocol = PROTOCOL
        self.client = IoTHubClient(connection_string, PROTOCOL)

        # set the time until a message times out
        self.client.set_option("messageTimeout", MESSAGE_TIMEOUT)
        # some embedded platforms need certificate information
        self.set_certificates()

    def set_certificates(self):
        isWindows = sys.platform.lower() in ['windows', 'win32']
        if not isWindows:
            CERT_FILE = os.environ['EdgeModuleCACertificateFile']        
            print("Adding TrustedCerts from: {0}".format(CERT_FILE))
            
            # this brings in x509 privateKey and certificate
            file = open(CERT_FILE)
            try:
                self.client.set_option("TrustedCerts", file.read())
                print ( "set_option TrustedCerts successful" )
            except IoTHubClientError as iothub_client_error:
                print ( "set_option TrustedCerts failed (%s)" % iothub_client_error )

            file.close()

    # Forwards the message received onto the next stage in the process.
    def send_analysis_to_output(self, msg):
        msg_txt = json.dumps(msg)
        hubmessage = IoTHubMessage(bytearray(msg_txt, 'utf8'))
        self.client.send_event_async("output1", hubmessage, device_message_callback, 0)
Пример #2
0
def iothub_client_init():
    # prepare iothub client
    client = IoTHubClient(CONNECTION_STRING, PROTOCOL)
    client.set_option("product_info", "HappyPath_RaspberryPi-Python")
    if client.protocol == IoTHubTransportProvider.HTTP:
        client.set_option("timeout", TIMEOUT)
        client.set_option("MinimumPollingTime", MINIMUM_POLLING_TIME)
    
    # set the time until a message times out
    client.set_option("messageTimeout", MESSAGE_TIMEOUT)
    
    # to enable MQTT logging set to 1
    # MQTT (Message Queuing Telemetry Transport) is an ISO standard, publish-subscribe based messaging protocol.
    # it works on the top of the TCP/IP protocol
    if client.protocol == IoTHubTransportProvider.MQTT:
        client.set_option("logtrace", 0)
    
    client.set_message_callback(receive_message_callback, RECEIVE_CONTEXT)

    # Device twins store device-related information that:
    # Device and back ends can use to synchronize device conditions and configuration.
    # The solution back end can use to query and target long-running operations.
    if client.protocol == IoTHubTransportProvider.MQTT or client.protocol == IoTHubTransportProvider.MQTT_WS:
        client.set_device_twin_callback(device_twin_callback, TWIN_CONTEXT)
        client.set_device_method_callback(device_method_callback, METHOD_CONTEXT)

    return client
class HubManager(object):

    def __init__(self, connection_string = None, protocol = IoTHubTransportProvider.MQTT):
        if not connection_string:
            connection_string = os.environ['EdgeHubConnectionString']

        print("\nPython %s\n" % sys.version)
        print("IoT Hub Client for Python")
        print("Starting the IoT Hub Python sample using protocol %s..." % protocol)

        self.client_protocol = protocol
        self.client = IoTHubClient(connection_string, protocol)

        # set the time until a message times out
        self.client.set_option("messageTimeout", MESSAGE_TIMEOUT)
        # some embedded platforms need certificate information
        self.set_certificates()

    def set_certificates(self):
        CERT_FILE = os.environ['EdgeModuleCACertificateFile']
        print("Adding TrustedCerts from: {0}".format(CERT_FILE))

        # this brings in x509 privateKey and certificate
        with open(CERT_FILE) as file:
            try:
                self.client.set_option("TrustedCerts", file.read())
                print("set_option TrustedCerts successful")
            except IoTHubClientError as iothub_client_error:
                print("set_option TrustedCerts failed (%s)" % iothub_client_error)
Пример #4
0
    def iothub_client_init(self):
        log = logger.getLogger()
        # prepare iothub client
        log.debug("- creating the client with {0} {1} {2} {3}".format(
            self.iothub_uri, self.device_id, self.security_type.name,
            self.protocol.name))
        client = IoTHubClient(self.iothub_uri, self.device_id,
                              self.security_type, self.protocol)

        # set the time until a message times out
        client.set_option("messageTimeout", self.MESSAGE_TIMEOUT)

        client.set_option("logtrace", 0)
        client.set_message_callback(self.receive_message_callback,
                                    self.RECEIVE_CONTEXT)
        client.set_device_twin_callback(self.device_twin_callback,
                                        self.TWIN_CONTEXT)
        client.set_device_method_callback(self.device_method_callback,
                                          self.METHOD_CONTEXT)
        client.set_connection_status_callback(self.connection_status_callback,
                                              self.CONNECTION_STATUS_CONTEXT)

        retryPolicy = IoTHubClientRetryPolicy.RETRY_INTERVAL
        retryInterval = 100
        client.set_retry_policy(retryPolicy, retryInterval)
        log.info("SetRetryPolicy to: retryPolicy = {0}".format(retryPolicy))
        log.info("SetRetryPolicy to: retryTimeoutLimitInSeconds = {0}".format(
            retryInterval))
        retryPolicyReturn = client.get_retry_policy()
        log.info("GetRetryPolicy returned: retryPolicy = {0}".format(
            retryPolicyReturn.retryPolicy))
        log.info("GetRetryPolicy returned: retryTimeoutLimitInSeconds = {0}\n".
                 format(retryPolicyReturn.retryTimeoutLimitInSeconds))

        return client
Пример #5
0
    def iothub_client_init(self):
        # prepare iothub client
        client = IoTHubClient(self.connectionString,
                              IoTHubTransportProvider.MQTT)

        # set the time until a message times out
        client.set_option("messageTimeout", self.MESSAGE_TIMEOUT)

        client.set_option("logtrace", 0)
        client.set_message_callback(self.receive_message_callback,
                                    self.RECEIVE_CONTEXT)
        client.set_device_twin_callback(self.device_twin_callback,
                                        self.TWIN_CONTEXT)
        client.set_device_method_callback(self.device_method_callback,
                                          self.METHOD_CONTEXT)
        client.set_connection_status_callback(self.connection_status_callback,
                                              self.CONNECTION_STATUS_CONTEXT)

        retryPolicy = IoTHubClientRetryPolicy.RETRY_INTERVAL
        retryInterval = 100
        client.set_retry_policy(retryPolicy, retryInterval)
        logger.log("SetRetryPolicy to: retryPolicy = {0}".format(retryPolicy))
        logger.log(
            "SetRetryPolicy to: retryTimeoutLimitInSeconds = {0}".format(
                retryInterval))
        retryPolicyReturn = client.get_retry_policy()
        logger.log("GetRetryPolicy returned: retryPolicy = {0}".format(
            retryPolicyReturn.retryPolicy))
        logger.log(
            "GetRetryPolicy returned: retryTimeoutLimitInSeconds = {0}\n".
            format(retryPolicyReturn.retryTimeoutLimitInSeconds))

        return client
Пример #6
0
def iothub_client_init():
    # prepare iothub client
    client = IoTHubClient(CONNECTION_STRING, PROTOCOL)
    # set the time until a message times out
    client.set_option("messageTimeout", MESSAGE_TIMEOUT)
    client.set_option("logtrace", 0)
    return client
Пример #7
0
    def iothubClientInit(self):
        # prepare iothub client
        client = IoTHubClient(self.CONNECTION_STRING, PROTOCOL)
        client.set_option("product_info", "HappyPath_RaspberryPi-Python")

        if client.protocol == IoTHubTransportProvider.HTTP:
            client.set_option("timeout", TIMEOUT)
            client.set_option("MinimumPollingTime", MINIMUM_POLLING_TIME)

        # set the time until a message times out
        client.set_option("messageTimeout", MESSAGE_TIMEOUT)

        # to enable MQTT logging set to 1
        if client.protocol == IoTHubTransportProvider.MQTT:
            client.set_option("logtrace", 0)

        # set callback after a message is received
        client.set_message_callback(self.receiveMessageCallback, RECEIVE_CONTEXT)

        # if MQTT or MQTT_WS is used -> set device twin callback
        if client.protocol == IoTHubTransportProvider.MQTT or client.protocol == IoTHubTransportProvider.MQTT_WS:
            client.set_device_twin_callback(self.deviceTwinCallback, TWIN_CONTEXT)
            client.set_device_method_callback(self.deviceMethodCallback, METHOD_CONTEXT)
            
        return client
Пример #8
0
class Sender(object):
    def __init__(self,
                 connection_string,
                 certificate_path=False,
                 protocol=PROTOCOL):
        self.client_protocol = protocol
        self.client = IoTHubClient(connection_string, protocol)
        # set the time until a message times out
        self.client.set_option('messageTimeout', MESSAGE_TIMEOUT)
        # some embedded platforms need certificate information
        if certificate_path:
            self.set_certificates(certificate_path)

    def set_certificates(self, certificate_path):
        file = open(certificate_path, 'r')
        try:
            self.client.set_option('TrustedCerts', file.read())
            print('IoT Edge TrustedCerts set successfully')
        except IoTHubClientError as iothub_client_error:
            print('Setting IoT Edge TrustedCerts failed (%s)' %
                  iothub_client_error)
        file.close()

    def send_event_to_output(self, message, properties, send_context):
        event = IoTHubMessage(bytearray(message, 'utf8'))
        if len(properties) > 0:
            prop_map = event.properties()
            for key in properties:
                prop_map.add_or_update(key, properties[key])

        self.client.send_event_async(event, send_confirmation_callback,
                                     send_context)
Пример #9
0
def iothub_client_init():
    # prepare iothub client
    client = IoTHubClient(CONNECTION_STRING, PROTOCOL)
    # set the time until a message times out
    client.set_option("messageTimeout", MESSAGE_TIMEOUT)
    # some embedded platforms need certificate information
    set_certificates(client)
    # to enable MQTT logging set to 1
    if client.protocol == IoTHubTransportProvider.MQTT:
        client.set_option("logtrace", 0)
    client.set_message_callback(receive_message_callback, RECEIVE_CONTEXT)
    if client.protocol == IoTHubTransportProvider.MQTT or client.protocol == IoTHubTransportProvider.MQTT_WS:
        client.set_device_twin_callback(device_twin_callback, TWIN_CONTEXT)
        client.set_device_method_callback(device_method_callback,
                                          METHOD_CONTEXT)
    if client.protocol == IoTHubTransportProvider.AMQP or client.protocol == IoTHubTransportProvider.AMQP_WS:
        client.set_connection_status_callback(connection_status_callback,
                                              CONNECTION_STATUS_CONTEXT)

    retryPolicy = IoTHubClientRetryPolicy.RETRY_INTERVAL
    retryInterval = 100
    client.set_retry_policy(retryPolicy, retryInterval)
    print("SetRetryPolicy to: retryPolicy = %d" % retryPolicy)
    print("SetRetryPolicy to: retryTimeoutLimitInSeconds = %d" % retryInterval)
    retryPolicyReturn = client.get_retry_policy()
    print("GetRetryPolicy returned: retryPolicy = %d" %
          retryPolicyReturn.retryPolicy)
    print("GetRetryPolicy returned: retryTimeoutLimitInSeconds = %d" %
          retryPolicyReturn.retryTimeoutLimitInSeconds)

    return client
Пример #10
0
def iothub_client_sample_run():

    try:
        # prepare iothub client
        client = IoTHubClient(CONNECTION_STRING, IoTHubTransportProvider.MQTT)
        # to enable MQTT logging set to 1
        client.set_option("logtrace", 0)
        client.set_message_callback(receive_message_callback, RECEIVE_CONTEXT)

        while True:
            # send a few messages every minute
            print ( "IoTHubClient sending message" )

            msg_txt_formatted = MSG_TXT % "This is a test"
            message = IoTHubMessage(msg_txt_formatted)

            client.send_event_async(message, send_confirmation_callback, SEND_CONTEXT)
            print ( "IoTHubClient.send_event_async accepted message for transmission to IoT Hub." )

            time.sleep(SLEEP_TIME)

    except IoTHubError as iothub_error:
        print ( "Unexpected error %s from IoTHub" % iothub_error )
        return
    except KeyboardInterrupt:
        print ( "IoTHubClient sample stopped" )
Пример #11
0
def iothub_client_init():
    logger.info("Initializing iothub_client")
    client = IoTHubClient(CONNECTION_STRING, PROTOCOL)
    if client.protocol == IoTHubTransportProvider.MQTT:
        client.set_option("logtrace", 0)
    client.set_device_method_callback(device_method_callback, 0)
    return client
def iothub_client_init():
    # prepare iothub client
    client = IoTHubClient(CONNECTION_STRING, PROTOCOL)
    # set the time until a message times out
    client.set_option("messageTimeout", MESSAGE_TIMEOUT)
    client.set_option("logtrace", 0)

    if client.protocol == IoTHubTransportProvider.MQTT or client.protocol == IoTHubTransportProvider.MQTT_WS:
        client.set_device_twin_callback(device_twin_callback, client)
    return client
def iothub_client_init(transport, device_name, device_key):
    # prepare iothub client with transport
    config = IoTHubConfig(PROTOCOL, device_name, device_key, "", IOTHUBNAME, IOTHUBSUFFIX, "")
    client = IoTHubClient(transport, config)

    # set the time until a message times out
    client.set_option("messageTimeout", MESSAGE_TIMEOUT)

    client.set_connection_status_callback(connection_status_callback, CONNECTION_STATUS_CONTEXT)

    return client
Пример #14
0
    def iothub_client_init(config, device):
        conn = "HostName={}.azure-devices.net;DeviceId={};SharedAccessKey={}".format(
            config[DOMAIN].get("host"), device[0], device[1].get("auth_key"))

        client = IoTHubClient(conn, IoTHubTransportProvider.MQTT)

        # # set the time until a message times out
        client.set_option("messageTimeout",
                          config[DOMAIN].get(CONF_MESSAGE_TIMEOUT))
        client.set_option("logtrace", config[DOMAIN].get(CONF_LOG_LEVEL))
        return client
Пример #15
0
def iothub_client_init():
    client = IoTHubClient(CONNECTION_STRING, PROTOCOL)
    
    client.set_message_callback(receive_message_callback, RECEIVE_CONTEXT)
    client.set_device_twin_callback(device_twin_callback, TWIN_CONTEXT) 
    client.set_device_method_callback(device_method_callback, METHOD_CONTEXT)

    client.set_option("messageTimeout", MESSAGE_TIMEOUT)
    client.set_option("logtrace", 0)

    return client
Пример #16
0
def iothub_client_init():
    # prepare iothub client
    client = IoTHubClient(CONNECTION_STRING, PROTOCOL)
    client.set_option("product_info", "RaspberryPi_test_button")
    client.set_option("messageTimeout", MESSAGE_TIMEOUT)
    client.set_message_callback(device_method_callback, RECEIVE_CONTEXT)
    #if client.protocol == IoTHubTransportProvider.MQTT or client.protocol == IoTHubTransportProvider.MQTT_WS:
    #    client.set_device_twin_callback(
    #        device_twin_callback, TWIN_CONTEXT)
    client.set_device_method_callback(device_method_callback, METHOD_CONTEXT)
    return client
Пример #17
0
def iothub_client_init():
    # Prepare iothub client
    client = IoTHubClient(CONNECTION_STRING, PROTOCOL)

    # Set the time until a message times out
    client.set_option("messageTimeout", MESSAGE_TIMEOUT)

    # Some embedded platforms need certificate information
    set_certificates(client)

    return client
Пример #18
0
def iothub_client_init():
    # prepare iothub client
    client = IoTHubClient(CONNECTION_STRING, PROTOCOL)

    # set options
    client.set_option("messageTimeout", MESSAGE_TIMEOUT)
    client.set_option("logtrace", 0)

    # set callbacks
    client.set_device_twin_callback(device_twin_callback, TWIN_CONTEXT)

    return client
def iothub_client_init(transport, device_name, device_key):
    # prepare iothub client with transport
    config = IoTHubConfig(PROTOCOL, device_name, device_key, "", IOTHUBNAME,
                          IOTHUBSUFFIX, "")
    client = IoTHubClient(transport, config)

    # set the time until a message times out
    client.set_option("messageTimeout", MESSAGE_TIMEOUT)

    client.set_connection_status_callback(connection_status_callback,
                                          CONNECTION_STATUS_CONTEXT)

    return client
Пример #20
0
def iothub_client_init():
    # prepare iothub client
    client = IoTHubClient(CONNECTION_STRING, PROTOCOL)
    # set the time until a message times out
    client.set_option("messageTimeout", MESSAGE_TIMEOUT)
    client.set_option("logtrace", 0)
    client.set_device_method_callback(
        device_method_callback,
        METHOD_CONTEXT)  #Anger vilken metod som anropas för att ta emot Method
    client.set_message_callback(
        receive_message_callback,
        RECEIVE_CONTEXT)  #Anger vilken medotd för hantering av meddelanden
    return client
Пример #21
0
def iothub_client_init():
    # prepare iothub client
    client = IoTHubClient(CONNECTION_STRING, PROTOCOL)
    # set the time until a message times out
    client.set_option("messageTimeout", MESSAGE_TIMEOUT)
    #Turn on and off log tracing for the transport
    client.set_option("logtrace", 0)
    #Anger vilken metod som anropas för att ta emot Method
    client.set_device_method_callback(device_method_callback, METHOD_CONTEXT)
    #Anger vilken medotd för hantering av meddelanden
    client.set_message_callback(receive_message_callback, RECEIVE_CONTEXT)
    client.set_device_twin_callback(device_twin_callback, METHOD_CONTEXT)
    #client.upload_blob_async(upload_to_blob, RECEIVE_CALLBACKS)
    return client
def iothub_client_init():
    # prepare iothub client
    client = IoTHubClient(CONNECTION_STRING, PROTOCOL)
    if client.protocol == IoTHubTransportProvider.HTTP:
        client.set_option("timeout", TIMEOUT)
        client.set_option("MinimumPollingTime", MINIMUM_POLLING_TIME)
    # set the time until a message times out
    client.set_option("messageTimeout", MESSAGE_TIMEOUT)


    # some embedded platforms need certificate information
    set_certificates(client)
    # to enable MQTT logging set to 1
    if client.protocol == IoTHubTransportProvider.MQTT:
        client.set_option("logtrace", 0)
    client.set_message_callback(
        receive_message_callback, RECEIVE_CONTEXT)
    if client.protocol == IoTHubTransportProvider.MQTT or client.protocol == IoTHubTransportProvider.MQTT_WS:
        client.set_device_twin_callback(
            device_twin_callback, TWIN_CONTEXT)
        client.set_device_method_callback(
            device_method_callback, METHOD_CONTEXT)


    return client
Пример #23
0
def iothub_client_init():
    client = IoTHubClient(DEVICE_CONNECTION_STRING, PROTOCOL)
    client.set_option("product_info", "RaspberryPi")
    if client.protocol == IoTHubTransportProvider.HTTP:
        client.set_option("timeout", TIMEOUT)
        client.set_option("MinimumPollingTime", MINIMUM_POLLING_TIME)
    client.set_option("messageTimeout", MESSAGE_TIMEOUT)
    if client.protocol == IoTHubTransportProvider.MQTT:
        client.set_option("logtrace", 0)
    if client.protocol == IoTHubTransportProvider.MQTT or client.protocol == IoTHubTransportProvider.MQTT_WS:
        client.set_device_twin_callback(device_twin_callback, TWIN_CONTEXT)
        client.set_device_method_callback(device_method_callback,
                                          METHOD_CONTEXT)
    return client
Пример #24
0
def iothub_client_init(ConString, Proto):
    logging.basicConfig(filename='smartlib{0}.log'.format(dt.date.today().isocalendar()[1]), level=logging.DEBUG)
    # prepare iothub client
    print("ConString {0}".format(ConString))
    client = IoTHubClient(ConString, Proto)
    if client.protocol == IoTHubTransportProvider.HTTP:
        client.set_option("timeout", TIMEOUT)
        client.set_option("MinimumPollingTime", MINIMUM_POLLING_TIME)
    # set the time until a message times out
    client.set_option("messageTimeout", MESSAGE_TIMEOUT)
    # some embedded platforms need certificate information
    set_certificates(client)
    # to enable MQTT logging set to 1
    if client.protocol == IoTHubTransportProvider.MQTT:
        client.set_option("logtrace", 0)
    client.set_message_callback(
        receive_message_callback, RECEIVE_CONTEXT)
    if client.protocol == IoTHubTransportProvider.MQTT or client.protocol == IoTHubTransportProvider.MQTT_WS:
        client.set_device_twin_callback(
            device_twin_callback, TWIN_CONTEXT)
        client.set_device_method_callback(
            device_method_callback, METHOD_CONTEXT)
    if client.protocol == IoTHubTransportProvider.AMQP or client.protocol == IoTHubTransportProvider.AMQP_WS:
        client.set_connection_status_callback(
            connection_status_callback, CONNECTION_STATUS_CONTEXT)

    retryPolicy = IoTHubClientRetryPolicy.RETRY_INTERVAL
    retryInterval = 0
    client.set_retry_policy(retryPolicy, retryInterval)
    print ( "SetRetryPolicy to: retryPolicy = %d" %  retryPolicy)
    print ( "SetRetryPolicy to: retryTimeoutLimitInSeconds = %d" %  retryInterval)
    retryPolicyReturn = client.get_retry_policy()
    print ( "GetRetryPolicy returned: retryPolicy = %d" %  retryPolicyReturn.retryPolicy)
    print ( "GetRetryPolicy returned: retryTimeoutLimitInSeconds = %d" %  retryPolicyReturn.retryTimeoutLimitInSeconds)
    return client
def iothub_client_init():
    # prepare iothub client
    client = IoTHubClient(CONNECTION_STRING, PROTOCOL)
    if client.protocol == IoTHubTransportProvider.HTTP:
        client.set_option("timeout", TIMEOUT)
        client.set_option("MinimumPollingTime", MINIMUM_POLLING_TIME)
    # set the time until a message times out
    client.set_option("messageTimeout", MESSAGE_TIMEOUT)
    # some embedded platforms need certificate information
    set_certificates(client)
    # to enable MQTT logging set to 1
    if client.protocol == IoTHubTransportProvider.MQTT:
        client.set_option("logtrace", 0)
    client.set_message_callback(
        receive_message_callback, RECEIVE_CONTEXT)
    if client.protocol == IoTHubTransportProvider.MQTT or client.protocol == IoTHubTransportProvider.MQTT_WS:
        client.set_device_twin_callback(
            device_twin_callback, TWIN_CONTEXT)
        client.set_device_method_callback(
            device_method_callback, METHOD_CONTEXT)
    if client.protocol == IoTHubTransportProvider.AMQP or client.protocol == IoTHubTransportProvider.AMQP_WS:
        client.set_connection_status_callback(
            connection_status_callback, CONNECTION_STATUS_CONTEXT)

    retryPolicy = IoTHubClientRetryPolicy.RETRY_INTERVAL
    retryInterval = 100
    client.set_retry_policy(retryPolicy, retryInterval)
    print ( "SetRetryPolicy to: retryPolicy = %d" %  retryPolicy)
    print ( "SetRetryPolicy to: retryTimeoutLimitInSeconds = %d" %  retryInterval)
    retryPolicyReturn = client.get_retry_policy()
    print ( "GetRetryPolicy returned: retryPolicy = %d" %  retryPolicyReturn.retryPolicy)
    print ( "GetRetryPolicy returned: retryTimeoutLimitInSeconds = %d" %  retryPolicyReturn.retryTimeoutLimitInSeconds)

    return client
Пример #26
0
class HubManager(object):
    def __init__(self, connection_string):
        self.client_protocol = PROTOCOL
        self.client = IoTHubClient(connection_string, PROTOCOL)
        self.conn = pymssql.connect('sql:1433', 'SA', 'Strong!Passw0rd',
                                    "MeasurementsDB")
        self.cursor = self.conn.cursor()

        # set the time until a message times out
        self.client.set_option("messageTimeout", MESSAGE_TIMEOUT)
        # some embedded platforms need certificate information
        self.set_certificates()

        # sets the callback when a message arrives on "input1" queue.  Messages sent to
        # other inputs or to the default will be silently discarded.
        self.client.set_message_callback("input1", receive_message_callback,
                                         self)

    def set_certificates(self):
        isWindows = sys.platform.lower() in ['windows', 'win32']
        if not isWindows:
            CERT_FILE = os.environ['EdgeModuleCACertificateFile']
            print("Adding TrustedCerts from: {0}".format(CERT_FILE))

            # this brings in x509 privateKey and certificate
            file = open(CERT_FILE)
            try:
                self.client.set_option("TrustedCerts", file.read())
                print("set_option TrustedCerts successful")
            except IoTHubClientError as iothub_client_error:
                print("set_option TrustedCerts failed (%s)" %
                      iothub_client_error)

            file.close()

    # Forwards the message received onto the next stage in the process.
    def forward_event_to_output(self, outputQueueName, event, send_context):
        self.client.send_event_async(outputQueueName, event,
                                     send_confirmation_callback, send_context)

    def store_to_db(self, sender, receiver):
        self.cursor.execute(
            'INSERT INTO MeasurementsDB.dbo.test (Sender, Receiver) Values ({0}, {1});'
            .format(sender, receiver))
        self.conn.commit()
        ts = int(time.time() * 1000)
        self.cursor.execute(
            'INSERT INTO MeasurementsDB.dbo.result (Sender, Receiver, DB) Values ({0}, {1}, {2});'
            .format(sender, receiver, ts))
Пример #27
0
def iothub_client_init():
    # prepare iothub client
    client = IoTHubClient(CONNECTION_STRING, PROTOCOL)
    client.set_option("messageTimeout", MESSAGE_TIMEOUT)
    client.set_option("logtrace", 0)
    client.set_message_callback(receive_message_callback, RECEIVE_CONTEXT)
    retryPolicy = IoTHubClientRetryPolicy.RETRY_INTERVAL
    retryInterval = 100
    client.set_retry_policy(retryPolicy, retryInterval)
    print ( "SetRetryPolicy to: retryPolicy = %d" %  retryPolicy)
    print ( "SetRetryPolicy to: retryTimeoutLimitInSeconds = %d" %  retryInterval)
    retryPolicyReturn = client.get_retry_policy()
    print ( "GetRetryPolicy returned: retryPolicy = %d" %  retryPolicyReturn.retryPolicy)
    print ( "GetRetryPolicy returned: retryTimeoutLimitInSeconds = %d" %  retryPolicyReturn.retryTimeoutLimitInSeconds)
    return client
Пример #28
0
def iothub_client_init():
    # prepare iothub client
    client = IoTHubClient(CONNECTION_STRING, IoTHubTransportProvider.MQTT)
    client.set_option("messageTimeout", MESSAGE_TIMEOUT)
    if client.protocol == IoTHubTransportProvider.MQTT:
        client.set_option("logtrace", 0)

    retryPolicy = IoTHubClientRetryPolicy.RETRY_INTERVAL
    retryInterval = 100
    client.set_retry_policy(retryPolicy, retryInterval)
    print ( "SetRetryPolicy to: retryPolicy = %d" %  retryPolicy)
    print ( "SetRetryPolicy to: retryTimeoutLimitInSeconds = %d" %  retryInterval)
    retryPolicyReturn = client.get_retry_policy()
    print ( "GetRetryPolicy returned: retryPolicy = %d" %  retryPolicyReturn.retryPolicy)
    print ( "GetRetryPolicy returned: retryTimeoutLimitInSeconds = %d" %  retryPolicyReturn.retryTimeoutLimitInSeconds)

    return client
Пример #29
0
def iothub_client_init():
    # prepare iothub client
    client = IoTHubClient(CONNECTION_STRING, PROTOCOL)
    client.set_option("product_info", "RaspberryPi-Python")
    client.set_option("timeout", TIMEOUT)
    client.set_option("MinimumPollingTime", MINIMUM_POLLING_TIME)
    # set the time until a message times out
    client.set_option("messageTimeout", MESSAGE_TIMEOUT)
    client.set_message_callback(receive_message_callback, RECEIVE_CONTEXT)
    return client
Пример #30
0
def iothub_client_init():
    # prepare iothub client
    client = IoTHubClient(CONNECTION_STRING, PROTOCOL)
    client.set_option("product_info", "HappyPath_RaspberryPi-Python")
    if client.protocol == IoTHubTransportProvider.HTTP:
        client.set_option("timeout", TIMEOUT)
        client.set_option("MinimumPollingTime", MINIMUM_POLLING_TIME)
    # set the time until a message times out
    client.set_option("messageTimeout", MESSAGE_TIMEOUT)
    return client
Пример #31
0
def initialize_client(connection_string):
    # prepare iothub client
    client = IoTHubClient(connection_string, PROTOCOL)
    client.set_option("product_info", "HappyPath_RaspberryPi-Python")
    if client.protocol == IoTHubTransportProvider.HTTP:
        client.set_option("timeout", TIMEOUT)
        client.set_option("MinimumPollingTime", MINIMUM_POLLING_TIME)
    # set the time until a message times out
    client.set_option("messageTimeout", MESSAGE_TIMEOUT)
    # to enable MQTT logging set to 1
    if client.protocol == IoTHubTransportProvider.MQTT:
        client.set_option("logtrace", 0)
    client.set_message_callback(receive_message_callback, RECEIVE_CONTEXT)
    if client.protocol == IoTHubTransportProvider.MQTT or client.protocol == IoTHubTransportProvider.MQTT_WS:
        client.set_device_twin_callback(device_twin_callback, TWIN_CONTEXT)
        client.set_device_method_callback(device_method_callback,
                                          METHOD_CONTEXT)
    return client
Пример #32
0
def iothub_client_init():
    # prepare iothub client
    client = IoTHubClient(CONNECTION_STRING, PROTOCOL)
    client.set_option("product_info", "HappyPath_RaspberryPi-Python")
    if client.protocol == IoTHubTransportProvider.HTTP:
        client.set_option("timeout", TIMEOUT)
        client.set_option("MinimumPollingTime", MINIMUM_POLLING_TIME)
    # set the time until a message times out
    client.set_option("messageTimeout", MESSAGE_TIMEOUT)
    # to enable MQTT logging set to 1
    if client.protocol == IoTHubTransportProvider.MQTT:
        client.set_option("logtrace", 0)
    client.set_message_callback(
        receive_message_callback, RECEIVE_CONTEXT)
    if client.protocol == IoTHubTransportProvider.MQTT or client.protocol == IoTHubTransportProvider.MQTT_WS:
        client.set_device_twin_callback(
            device_twin_callback, TWIN_CONTEXT)
        client.set_device_method_callback(
            device_method_callback, METHOD_CONTEXT)
    return client
Пример #33
0
class HubManager(object):

    def __init__(
            self,
            connection_string):
        self.client_protocol = PROTOCOL
        self.client = IoTHubClient(connection_string, PROTOCOL)

        # set the time until a message times out
        self.client.set_option("messageTimeout", MESSAGE_TIMEOUT)
        # some embedded platforms need certificate information
        self.set_certificates()
        
        # set a TWIN callback
        self.client.set_device_twin_callback(device_twin_callback, self)

        # sets the callback when a message arrives on "input1" queue.  Messages sent to 
        # other inputs or to the default will be silently discarded.
        self.client.set_message_callback("input1", receive_message_callback, self)

    def set_certificates(self):
        isWindows = sys.platform.lower() in ['windows', 'win32']
        if not isWindows:
            CERT_FILE = os.environ['EdgeModuleCACertificateFile']        
            print("Adding TrustedCerts from: {0}".format(CERT_FILE))
            
            # this brings in x509 privateKey and certificate
            file = open(CERT_FILE)
            try:
                self.client.set_option("TrustedCerts", file.read())
                print ( "set_option TrustedCerts successful" )
            except IoTHubClientError as iothub_client_error:
                print ( "set_option TrustedCerts failed (%s)" % iothub_client_error )

            file.close()

    # Forwards the message received onto the next stage in the process.
    def forward_event_to_output(self, outputQueueName, event, send_context):
        self.client.send_event_async(
            outputQueueName, event, send_confirmation_callback, send_context)
class HubManager(object):

    def __init__(
            self,
            connection_string,
            protocol=IoTHubTransportProvider.MQTT):
        self.client_protocol = protocol
        self.client = IoTHubClient(connection_string, protocol)
        if protocol == IoTHubTransportProvider.HTTP:
            self.client.set_option("timeout", TIMEOUT)
            self.client.set_option("MinimumPollingTime", MINIMUM_POLLING_TIME)
        # set the time until a message times out
        self.client.set_option("messageTimeout", MESSAGE_TIMEOUT)
        # some embedded platforms need certificate information
        # self.set_certificates()
        self.client.set_message_callback(receive_message_callback, RECEIVE_CONTEXT)
        self.client.set_device_twin_callback(device_twin_callback, TWIN_CONTEXT)
        self.client.set_device_method_callback(device_method_callback, METHOD_CONTEXT)

    def set_certificates(self):
        from iothub_client_cert import CERTIFICATES
        try:
            self.client.set_option("TrustedCerts", CERTIFICATES)
            print ( "set_option TrustedCerts successful" )
        except IoTHubClientError as iothub_client_error:
            print ( "set_option TrustedCerts failed (%s)" % iothub_client_error )

    def send_event(self, event, properties, send_context):
        if not isinstance(event, IoTHubMessage):
            event = IoTHubMessage(bytearray(event, 'utf8'))

        if len(properties) > 0:
            prop_map = event.properties()
            for key in properties:
                prop_map.add_or_update(key, properties[key])

        self.client.send_event_async(
            event, send_confirmation_callback, send_context)

    def send_reported_state(self, reported_state, size, user_context):
        self.client.send_reported_state(
            reported_state, size,
            send_reported_state_callback, user_context)

    def upload_to_blob(self, destinationfilename, source, size, usercontext):
        self.client.upload_blob_async(
            destinationfilename, source, size,
            blob_upload_conf_callback, usercontext)
Пример #35
0
def iothub_client_init():
    # prepare iothub client
    client = IoTHubClient(AzureHubConnectionString, PROTOCOL)
    if client.protocol == IoTHubTransportProvider.HTTP:
        client.set_option("timeout", TIMEOUT)
        client.set_option("MinimumPollingTime", MINIMUM_POLLING_TIME)
    # set the time until a message times out
    client.set_option("messageTimeout", MESSAGE_TIMEOUT)
    # to enable MQTT logging set to 1
    if client.protocol == IoTHubTransportProvider.MQTT:
        client.set_option("logtrace", 0)
    client.set_message_callback(receive_message_callback, RECEIVE_CONTEXT)
    # if client.protocol == IoTHubTransportProvider.MQTT or client.protocol == IoTHubTransportProvider.MQTT_WS:
    #     client.set_device_method_callback(
    #         device_method_callback, METHOD_CONTEXT)
    return client
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 iothub_client_init():
    # prepare iothub client
    client = IoTHubClient(CONNECTION_STRING, PROTOCOL)

    # HTTP specific settings
    if client.protocol == IoTHubTransportProvider.HTTP:
        client.set_option("timeout", TIMEOUT)
        client.set_option("MinimumPollingTime", MINIMUM_POLLING_TIME)

    # set the time until a message times out
    client.set_option("messageTimeout", MESSAGE_TIMEOUT)

    # this brings in x509 privateKey and certificate
    client.set_option("x509certificate", X509_CERTIFICATE)
    client.set_option("x509privatekey", X509_PRIVATEKEY)

    # to enable MQTT logging set to 1
    if client.protocol == IoTHubTransportProvider.MQTT:
        client.set_option("logtrace", 0)

    client.set_message_callback(
        receive_message_callback, RECEIVE_CONTEXT)
    return client
Пример #38
0
def run_e2e_device_client(iothub_service_client_messaging, iothub_device_method, iothub_device_twin, device_id, device_connection_string, protocol, authMethod):
    global IOTHUB_E2E_X509_CERT
    global IOTHUB_E2E_X509_THUMBPRINT
    global IOTHUB_E2E_X509_PRIVATE_KEY
    global CERTIFICATES
    global MESSAGING_CONTEXT

    ###########################################################################
    # IoTHubClient

    # prepare
    # act
    device_client = IoTHubClient(device_connection_string, protocol)

    # verify
    assert isinstance(device_client, IoTHubClient), 'Error: Invalid type returned!'
    assert device_client != None, "Error: device_client is NULL"
    ###########################################################################

    ###########################################################################
    # set_option

    # prepare
    # act
    device_client.set_option("messageTimeout", DEVICE_MESSAGE_TIMEOUT)

    if authMethod == IoTHubRegistryManagerAuthMethod.X509_THUMBPRINT:
        device_client.set_option("x509certificate", IOTHUB_E2E_X509_CERT)
        device_client.set_option("x509privatekey", IOTHUB_E2E_X509_PRIVATE_KEY)

    if device_client.protocol == IoTHubTransportProvider.HTTP:
        device_client.set_option("timeout", HTTP_TIMEOUT)
        device_client.set_option("MinimumPollingTime", HTTP_MINIMUM_POLLING_TIME)

    device_client.set_option("TrustedCerts", CERTIFICATES)
    device_client.set_option("logtrace", True)

    # verify
    ###########################################################################

    ###########################################################################
    # set_message_callback
    
    # prepare
    # act
    device_client.set_message_callback(receive_message_callback, MESSAGING_CONTEXT)
    ###########################################################################

    ###########################################################################
    # set_connection_status_callback
    
    # prepare
    # act
    device_client.set_connection_status_callback(connection_status_callback, CONNECTION_STATUS_CONTEXT)
    ###########################################################################

    # verify
    ###########################################################################

    if protocol == IoTHubTransportProvider.MQTT or protocol == IoTHubTransportProvider.MQTT_WS:
        ###########################################################################
        # set_device_twin_callback
    
        # prepare
        # act
        device_client.set_device_twin_callback(device_twin_callback, MESSAGING_CONTEXT)

        # verify
        ###########################################################################

        ###########################################################################
        # set_device_method_callback
    
        # prepare
        # act
        device_client.set_device_method_callback(device_method_callback, MESSAGING_CONTEXT)

        # verify
        ###########################################################################

        ###########################################################################
        # update device twin

        # prepare
        global TWIN_CALLBACK_EVENT
        global TWIN_CALLBACK_COUNTER

        TWIN_CALLBACK_EVENT.clear()
        TWIN_CALLBACK_COUNTER = 0

        # act
        sc_update_twin(iothub_device_twin, device_id)
        TWIN_CALLBACK_EVENT.wait(CALLBACK_TIMEOUT)

        # verify
        assert TWIN_CALLBACK_COUNTER > 0, "Error: device_twin_callback callback has not been called"
        ###########################################################################

        ###########################################################################
        # call device method

        # prepare
        global DEVICE_METHOD_EVENT
        global DEVICE_METHOD_CALLBACK_COUNTER

        DEVICE_METHOD_EVENT.clear()
        DEVICE_METHOD_CALLBACK_COUNTER = 0

        method_name = "E2EMethodName"
        payload_json = "{\"method_number\":\"42\"}"

        # act
        sc_invoke_device_method(iothub_device_method, device_id, method_name, payload_json)
        DEVICE_METHOD_EVENT.wait(CALLBACK_TIMEOUT)

        # verify
        assert DEVICE_METHOD_CALLBACK_COUNTER > 0, "Error: device_twin_callback callback has not been called"
        ###########################################################################

    if protocol == IoTHubTransportProvider.AMQP \
       or protocol == IoTHubTransportProvider.AMQP_WS \
       or protocol == IoTHubTransportProvider.MQTT \
       or protocol == IoTHubTransportProvider.MQTT_WS:
        ###########################################################################
        # send_reported_state
    
        # prepare
        global REPORTED_STATE_EVENT
        global REPORTED_STATE_CALLBACK_COUNTER

        reported_state = "{\"newState\":\"standBy\"}"
        REPORTED_STATE_EVENT.clear()
        REPORTED_STATE_CALLBACK_COUNTER = 0

        # act
        device_client.send_reported_state(reported_state, len(reported_state), send_reported_state_callback, REPORTED_STATE_CONTEXT)
        REPORTED_STATE_EVENT.wait(CALLBACK_TIMEOUT)

        # verify
        assert REPORTED_STATE_CALLBACK_COUNTER > 0, "Error: send_reported_state_callback has not been called"
        ###########################################################################

    ###########################################################################
    # set_retry_policy
    # get_retry_policy
   
    # prepare
    # act
    retryPolicy = IoTHubClientRetryPolicy.RETRY_INTERVAL
    retryInterval = 100
    device_client.set_retry_policy(retryPolicy, retryInterval)
    print ( "SetRetryPolicy to: retryPolicy = %d" %  retryPolicy)
    print ( "SetRetryPolicy to: retryTimeoutLimitInSeconds = %d" %  retryInterval)
    # verify
    retryPolicyReturn = device_client.get_retry_policy()
    assert retryPolicyReturn.retryPolicy == IoTHubClientRetryPolicy.RETRY_INTERVAL, "Error: set_retry_policy/get_retry_policy failed"
    assert retryPolicyReturn.retryTimeoutLimitInSeconds == 100, "Error: set_retry_policy/get_retry_policy failed"
    print ( "GetRetryPolicy returned: retryPolicy = %d" %  retryPolicyReturn.retryPolicy)
    print ( "GetRetryPolicy returned: retryTimeoutLimitInSeconds = %d" %  retryPolicyReturn.retryTimeoutLimitInSeconds)

    ###########################################################################
    # send_event_async

    # prepare
    global MESSAGING_MESSAGE
    global MESSAGE_RECEIVE_EVENT
    global MESSAGE_RECEIVE_CALLBACK_COUNTER

    MESSAGING_MESSAGE = ''.join([random.choice(string.ascii_letters) for n in range(12)])
    message = IoTHubMessage(bytearray(MESSAGING_MESSAGE, 'utf8'))
    MESSAGE_RECEIVE_EVENT.clear()
    MESSAGE_RECEIVE_CALLBACK_COUNTER = 0

    # act
    sc_send_message(iothub_service_client_messaging, device_id, message)
    MESSAGE_RECEIVE_EVENT.wait(CALLBACK_TIMEOUT)

    # verify
    assert MESSAGE_RECEIVE_CALLBACK_COUNTER > 0, "Error: message has not been received"
    ###########################################################################

    ###########################################################################
    # get_send_status

    # prepare
    status_counter = 0
    status = -1;

    # act
    while status_counter < 1:
        status = device_client.get_send_status()
        print ( "Send status: {0}".format(status) )

        # verify
        assert status == 0, "get_send_status reported status is not IDLE"
        status_counter += 1
    ###########################################################################


    if protocol != IoTHubTransportProvider.AMQP \
       and protocol != IoTHubTransportProvider.AMQP_WS:
        ###########################################################################
        # get_last_message_receive_time

        # prepare
        last_receive_time = -1
        # act
        last_receive_time = device_client.get_last_message_receive_time()

        # verify
        assert last_receive_time > 0, "Error: get_last_message_receive_time failed"
        ###########################################################################


    ###########################################################################
    # upload_blob_async
    
    # prepare
    global BLOB_UPLOAD_CONTEXT
    global BLOB_UPLOAD_EVENT
    global BLOB_UPLOAD_CALLBACK_COUNTER

    destination_file_name = ''.join([random.choice(string.ascii_letters) for n in range(12)])
    source = "Blob content for file upload test!"
    size = 34
    BLOB_UPLOAD_EVENT.clear()
    BLOB_UPLOAD_CALLBACK_COUNTER = 0

    # act
    device_client.upload_blob_async(destination_file_name, source, size, blob_upload_conf_callback, BLOB_UPLOAD_CONTEXT)
    BLOB_UPLOAD_EVENT.wait(CALLBACK_TIMEOUT)

    # verify
    assert BLOB_UPLOAD_CALLBACK_COUNTER > 0, "Error: blob_upload_conf_callback callback has not been called"
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
Пример #40
0
def run_e2e_shared_transport(iothub_registry_manager, iothub_service_client_messaging, iothub_device_method, iothub_device_twin, protocol, authMethod):
    global IOTHUB_CONNECTION_STRING
    global IOTHUB_E2E_X509_CERT
    global IOTHUB_E2E_X509_THUMBPRINT
    global IOTHUB_E2E_X509_PRIVATE_KEY
    global CERTIFICATES
    global DEVICE_MESSAGE_TIMEOUT
    global MESSAGING_MESSAGE
    global MESSAGE_RECEIVE_EVENT
    global MESSAGE_RECEIVE_CALLBACK_COUNTER

    print ("********************* run_e2e({0}, {1}) E2E test with shared transport started".format(protocol, authMethod))
    try:
        # Process connection string
        host_name_start = IOTHUB_CONNECTION_STRING.find("HostName")
        host_name_end = IOTHUB_CONNECTION_STRING.find(";", host_name_start)
        host_name_equal_sign = IOTHUB_CONNECTION_STRING.find("=", host_name_start)
        host_name_suffix_separator = IOTHUB_CONNECTION_STRING.find(".", host_name_equal_sign)

        iothub_name = IOTHUB_CONNECTION_STRING[host_name_equal_sign+1:host_name_suffix_separator]
        iothub_suffix = IOTHUB_CONNECTION_STRING[host_name_suffix_separator+1:host_name_end]

        # Create transport
        transport = IoTHubTransport(protocol, iothub_name, iothub_suffix)

        # Create first device
        device_id1 = generate_device_name()
        device = sc_create_device(iothub_registry_manager, device_id1, authMethod)
        iothub_device1 = iothub_registry_manager.get_device(device_id1)
        assert isinstance(iothub_device1, IoTHubDevice), 'Invalid type returned!'
        assert iothub_device1 != None, "iothub_device is NULL"
        device_key1 = iothub_device1.primaryKey
        device_sas_token1 = ""
        protocol_gateway_host_name1 = ""
        config1 = IoTHubConfig(protocol, device_id1, device_key1, device_sas_token1, iothub_name, iothub_suffix, protocol_gateway_host_name1)

        # Create second device
        device_id2 = generate_device_name()
        device = sc_create_device(iothub_registry_manager, device_id2, authMethod)
        iothub_device2 = iothub_registry_manager.get_device(device_id2)
        assert isinstance(iothub_device2, IoTHubDevice), 'Invalid type returned!'
        assert iothub_device2 != None, "iothub_device is NULL"
        device_key2 = iothub_device2.primaryKey
        device_sas_token2 = ""
        protocol_gateway_host_name3 = ""
        config2 = IoTHubConfig(protocol, device_id2, device_key2, device_sas_token2, iothub_name, iothub_suffix, protocol_gateway_host_name3)

        device_client1 = IoTHubClient(transport, config1)
        device_client2 = IoTHubClient(transport, config2)

        device_client1.set_option("messageTimeout", DEVICE_MESSAGE_TIMEOUT)
        device_client2.set_option("messageTimeout", DEVICE_MESSAGE_TIMEOUT)

        device_client1.set_message_callback(receive_message_callback, MESSAGING_CONTEXT)
        device_client2.set_message_callback(receive_message_callback, MESSAGING_CONTEXT)

        device_client1.set_connection_status_callback(connection_status_callback, CONNECTION_STATUS_CONTEXT)
        device_client2.set_connection_status_callback(connection_status_callback, CONNECTION_STATUS_CONTEXT)

        ###########################################################################
        # send_event_async

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

        # act
        sc_send_message(iothub_service_client_messaging, device_id1, message)
        MESSAGE_RECEIVE_EVENT.wait(CALLBACK_TIMEOUT)

        MESSAGE_RECEIVE_EVENT.clear()
        sc_send_message(iothub_service_client_messaging, device_id2, message)
        MESSAGE_RECEIVE_EVENT.wait(CALLBACK_TIMEOUT)

        # verify
        assert MESSAGE_RECEIVE_CALLBACK_COUNTER > 1, "Error: message has not been received"
        ###########################################################################

        retval = 0
    except Exception as e:
        print ("(********************* run_e2e({0}, {1}) E2E test with shared transport failed with exception: {2}".format(protocol, authMethod, e))
        retval = 1
    finally:
        sc_delete_device(iothub_registry_manager, device_id1)
        sc_delete_device(iothub_registry_manager, device_id2)

    print ("********************* run_e2e({0}, {1}) E2E test with shared transport finished".format(protocol, authMethod))
    return retval