Writing Methods in Python

To enable Device Cloud to call a method from a trigger, the thing details page, or a campaign, write the method callback and register the callback function.

The thing definition that corresponds to your application must have the method defined, including the notification variables (parameters). For more information about defining methods, see Device Cloud Management Portal User's Guide: Defining Methods.

You need to know the method key defined in the thing definition.

For notification variables, you need to know the key and the data type.

To receive methods, the application must be connected to Device Cloud.

  1. Write the callback function as follows:
    1. Specify the function signature based on whether you want to define the method with parameters and if you want to return update messages to the mailbox of the thing.

      This example is for a method that has parameters, needs user data, and sends an acknowledgment or progress update to Device Cloud.

      def my_action(client, params, user_data, request):
    2. Process any required parameters.

      For the parameter name, specify the notification variable key defined for the method in the thing definition.

      my_param = params.get("myParmName")
      # Process the value of my_param
    3. (Optional) Send one or more progress updates to Device Cloud.
      client.action_progress_update(request.request_id, "Progress message")

      When the application runs, the message appears in the mailbox of the thing.

    4. Return a status code and optionally, a status message.

      Specify an empty string for the status message if the result is successful.

      return (iot.STATUS_SUCCESS, "")

      When the application runs, the return status and message appear in the mailbox logs, and the message appears in the output box when the method is called from the thing page. If the status message is a not an empty string, the status in the mailbox appears as completed-error)

  2. Register the callback.

    For the action_name parameter, specify the method key defined in the thing definition.

    OptionDescription

    If you used a function as the callback, register the function callback.

    action_register_callback("my_action_name", my_action)

    If you implemented the method as a script, register the command.

    action_register_command("my_command_name",  "/path/To/my_action.sh")

    If you register more than one callback (for example, a callback function and a script), the register function returns an error.

When your application runs, the methods appear on the thing details page under the Methods tab.

Examples

The iot-simple-actions.py sample application provided with the agent shows example code for methods.