def iothub_devicemethod_sample_run():
    try:
        # Connect to your hub.
        iothub_device_method = IoTHubDeviceMethod(CONNECTION_STRING)

        # Call the direct method.
        response = iothub_device_method.invoke(DEVICE_ID, METHOD_NAME,
                                               METHOD_PAYLOAD, TIMEOUT)

        print("")
        print("Device Method called")
        print("Device Method name       : {0}".format(METHOD_NAME))
        print("Device Method payload    : {0}".format(METHOD_PAYLOAD))
        print("")
        print("Response status          : {0}".format(response.status))
        print("Response payload         : {0}".format(response.payload))

        input("Press Enter to continue...\n")

    except IoTHubError as iothub_error:
        print("")
        print("Unexpected error {0}".format(iothub_error))
        return
    except KeyboardInterrupt:
        print("")
        print("IoTHubDeviceMethod sample stopped")
Exemple #2
0
def iothub_devicemethod_sample_run():

    try:
        iothub_device_method = IoTHubDeviceMethod(CONNECTION_STRING)

        response = iothub_device_method.invoke(DEVICE_ID, METHOD_NAME,
                                               METHOD_PAYLOAD, TIMEOUT)

        print("")
        print("Device Method called")
        print("Device Method name       : {0}".format(METHOD_NAME))
        print("Device Method payload    : {0}".format(METHOD_PAYLOAD))
        print("")
        print("Response status          : {0}".format(response.status))
        print("Response payload         : {0}".format(response.payload))

        try:
            # Try Python 2.xx first
            raw_input("Press Enter to continue...\n")
        except:
            pass
            # Use Python 3.xx in the case of exception
            input("Press Enter to continue...\n")

    except IoTHubError as iothub_error:
        print("")
        print("Unexpected error {0}".format(iothub_error))
        return
    except KeyboardInterrupt:
        print("")
        print("IoTHubDeviceMethod sample stopped")
def methodUpdate(METHOD_NAME, METHOD_PAYLOAD):
    try:

        if DEVICE_STATUS == False:
            raise ConnectionError()
        iothub_device_method = IoTHubDeviceMethod(CONNECTION_STRING)

        #Skickar själva meddelandet och tar emot response
        response = iothub_device_method.invoke(DEVICE_ID, METHOD_NAME,
                                               METHOD_PAYLOAD, TIMEOUT)
        #Vad som skickades
        print("")
        print("Device Method called")
        print("Device Method name       : {0}".format(METHOD_NAME))
        print("Device Method payload    : {0}".format(METHOD_PAYLOAD))
        print("")
        print("Response status          : {0}".format(
            response.status))  #200 kan t.ex vara Success
        print("Response payload         : {0}".format(response.payload)
              )  #Själva svaret från devicen. Tex Device starta utan problem

        #raise IoTHubDeviceMethodError
    except:
        print("")
        print("")
        print("")
        print("Oops!", sys.exc_info()[0], "occured.")
        print("ERROR No deviced connected")
        print("")
def iothub_devicemethod_sample_run():

    try:
        iothub_device_method = IoTHubDeviceMethod(CONNECTION_STRING)

        response = iothub_device_method.invoke(DEVICE_ID, METHOD_NAME, METHOD_PAYLOAD, TIMEOUT)

        print ( "" )
        print ( "Device Method called" )
        print ( "Device Method name       : {0}".format(METHOD_NAME) )
        print ( "Device Method payload    : {0}".format(METHOD_PAYLOAD) )
        print ( "" )
        print ( "Response status          : {0}".format(response.status) )
        print ( "Response payload         : {0}".format(response.payload) )

        try:
            # Try Python 2.xx first
            raw_input("Press Enter to continue...\n")
        except:
            pass
            # Use Python 3.xx in the case of exception
            input("Press Enter to continue...\n")

    except IoTHubError as iothub_error:
        print ( "" )
        print ( "Unexpected error {0}".format(iothub_error) )
        return
    except KeyboardInterrupt:
        print ( "" )
        print ( "IoTHubDeviceMethod sample stopped" )
Exemple #5
0
def invoke_device(hub_name, device_id, method_name):
    if not hub_name or not device_id or not method_name or not hub_name in SERVICE_CONNECTION_STRINGS:
        return None
    connection_string = SERVICE_CONNECTION_STRINGS[hub_name]
    if not connection_string:
        return None

    try:
        iothub_device_method = IoTHubDeviceMethod(connection_string)
        response = iothub_device_method.invoke(device_id, method_name, METHOD_PAYLOAD, TIMEOUT)
        return response
    except IoTHubError as iothub_error:
        print('Error occurred: {}'.format(iothub_error))
        return None
Exemple #6
0
    def _get_diagnostics_method(self):
        self._enable_cors()
        try:
            byte_str = request.body.read()
            text_obj = byte_str.decode('UTF-8')
            post = json.loads(text_obj)
            method_name = str(post['method_name'])
            print("    Method Name         = {0}".format(method_name))
            method_payload = str(post['payload'])
            print("    Method payload         = {0}".format(method_payload))
            iothub_device_method = IoTHubDeviceMethod(CONNECTION_STRING)
            response = iothub_device_method.invoke(DEVICE_ID, method_name,
                                                   method_payload, 60)
        except Exception as err:
            return str(err)

        return "200 OK\n"
def iothub_firmware_sample_run():
    try:
        iothub_twin_method = IoTHubDeviceTwin(CONNECTION_STRING)

        print("")
        print("Direct Method called.")
        iothub_device_method = IoTHubDeviceMethod(CONNECTION_STRING)

        response = iothub_device_method.invoke(DEVICE_ID, METHOD_NAME,
                                               METHOD_PAYLOAD, TIMEOUT)
        print(response.payload)

        print("")
        print("Device Twin queried, press Ctrl-C to exit")
        while True:
            twin_info = iothub_twin_method.get_twin(DEVICE_ID)

            if "\"firmwareStatus\":\"standBy\"" in twin_info:
                print("Waiting on device...")
            elif "\"firmwareStatus\":\"downloading\"" in twin_info:
                print("Downloading firmware...")
            elif "\"firmwareStatus\":\"applying\"" in twin_info:
                print("Download complete, applying firmware...")
            elif "\"firmwareStatus\":\"completed\"" in twin_info:
                print("Firmware applied")
                print("")
                print("Get reported properties from device twin:")
                print(twin_info)
                break
            else:
                print("Unknown status")

            status_counter = 0
            while status_counter <= MESSAGE_COUNT:
                time.sleep(1)
                status_counter += 1

    except IoTHubError as iothub_error:
        print("")
        print("Unexpected error {0}" % iothub_error)
        return
    except KeyboardInterrupt:
        print("")
        print("IoTHubService sample stopped")
Exemple #8
0
def iothub_devicemethod_sample_run():

    try:
        print("Send Method to IOT Device, input Start or Stop: ")
        print("Press 1 to Start the service or 2 to stop it: ")
        while True:

            inp = int((input()))
            if inp == 1:
                METHOD_NAME="Start"
                METHOD_PAYLOAD = "{\"StartService\":\"42\"}"
            elif inp == 2:
                METHOD_NAME="Stop"
                METHOD_PAYLOAD = "{\"StopService\":\"42\"}"
            iothub_device_method = IoTHubDeviceMethod(CONNECTION_STRING)

            response = iothub_device_method.invoke(DEVICE_ID, METHOD_NAME, METHOD_PAYLOAD, TIMEOUT)

            print ( "" )
            print ( "Device Method called" )
            print ( "Device Method name       : {0}".format(METHOD_NAME) )
            print ( "Device Method payload    : {0}".format(METHOD_PAYLOAD) )
            print ( "" )
            print ( "Response status          : {0}".format(response.status) )
            print ( "Response payload         : {0}".format(response.payload) )

        
        try:
            # Try Python 2.xx first
            raw_input("Press Enter to continue...\n")
        except:
            pass
            # Use Python 3.xx in the case of exception
            input("Press Enter to continue...\n")

    except IoTHubError as iothub_error:
        print ( "" )
        print ( "Unexpected error {0}".format(iothub_error) )
        return
    except KeyboardInterrupt:
        print ( "" )
        print ( "IoTHubDeviceMethod sample stopped" )
def iothub_devicemethod_sample_run():
    try:
        iothub_twin_method = IoTHubDeviceTwin(CONNECTION_STRING)
        iothub_device_method = IoTHubDeviceMethod(CONNECTION_STRING)

        print("")
        print("Invoking device to reboot...")

        response = iothub_device_method.invoke(DEVICE_ID, METHOD_NAME,
                                               METHOD_PAYLOAD, TIMEOUT)

        print("")
        print("Successfully invoked the device to reboot.")

        print("")
        print(response.payload)

        while True:
            print("")
            print("IoTHubClient waiting for commands, press Ctrl-C to exit")

            status_counter = 0
            while status_counter <= WAIT_COUNT:
                twin_info = iothub_twin_method.get_twin(DEVICE_ID)

                if twin_info.find("rebootTime") != -1:
                    print("Last reboot time: " +
                          twin_info[twin_info.find("rebootTime") +
                                    11:twin_info.find("rebootTime") + 37])
                else:
                    print("Waiting for device to report last reboot time...")

                time.sleep(5)
                status_counter += 1

    except IoTHubError as iothub_error:
        print("")
        print("Unexpected error {0}".format(iothub_error))
        return
    except KeyboardInterrupt:
        print("")
        print("IoTHubDeviceMethod sample stopped")
Exemple #10
0
    def _get_run_command(self):
        self._enable_cors()
        try:
            byte_str = request.body.read()
            text_obj = byte_str.decode('UTF-8')
            post = json.loads(text_obj)
            print("POST DATA:")
            print(post)
            method_name = str(post['method_name'])
            print("    Method Name         = {0}".format(method_name))
            method_payload = dict()
            method_payload["cmd"] = str(post['cmd'])
            print("    Method payload         = {0}".format(method_payload))
            iothub_device_method = IoTHubDeviceMethod(CONNECTION_STRING)
            response = iothub_device_method.invoke(DEVICE_ID, method_name,
                                                   str(method_payload), 60)
        except Exception as err:
            print("ERROR is:")
            print(str(err))
            return str(err)

        return "200 OK\n"
Exemple #11
0
def sc_create_device_method(iothub_connection_string):
    iothub_device_method = IoTHubDeviceMethod(IOTHUB_CONNECTION_STRING)
    assert iothub_device_method != None, "iothub_device_method is NULL"
    return iothub_device_method
Exemple #12
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
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