Add More Traits and Handlers

  • You can add multiple traits to your device model, which are not limited to specific device types.

  • To add a new trait and handle commands, you need to modify the hotword.py file by adding a code block for the specific command.

  • You can find information on the command-name and parameter-name variables by referring to the trait's documentation page under the Device COMMANDS table.

  • After modifying the code, you need to update the device model and run the updated source code to test the new trait functionality.

You can add as many traits to your device model as you wish. These traits are not tied to just one device type, you can use them as you choose.

This is the process to add any trait and handle the incoming command:

  1. Determine which trait you want to add.

  2. Open the hotword.py file.

    cd assistant-sdk-python/google-assistant-sdk/googlesamples/assistant/library
    nano hotword.py
  3. Add the following code block under the existing one that handles the action.devices.commands.OnOff command (don't delete the existing code block).

    if command == "action.devices.commands.command-name":
        if params['parameter-name']:
            if conditional:
                print('Something happened.')
            else:
                print('Something else happened.')
  4. Find the information you need for each variable in the above code block.

    command-nameGo to the specific trait page from Step 1 (for example, ColorTemperature). Use a command from the Device COMMANDS table.
    parameter-nameLook again at the Device COMMANDS table on the trait page. Each command has one or more parameters associated with it. These are listed under "params" in the EXECUTE request JSON. Use the exact parameter name. Note that some of these parameters are objects that contain other parameters - just use the top-level object.
    conditionalYou don't strictly need to use a conditional in your handler code, but it may help to differentiate how you execute the command on the device.

    Here are some examples for traits Brightness and ColorTemperature:

    if command == "action.devices.commands.BrightnessAbsolute":
        if params['brightness']:
            if params['brightness'] > 50:
                print('brightness > 50')
            else:
                print('brightness <= 50')
    
    if command == "action.devices.commands.ColorAbsolute":
        if params['color']:
            if params['color'].get('name') == "blue":
                print('The color is blue.')
            else:
                print('The color is not blue.')
  5. Update the device model with the trait you added in Step 1.

  6. Run the modified source code.

    cd assistant-sdk-python/google-assistant-sdk/googlesamples/assistant/library
    python hotword.py --device-model-id my-model
  7. Try a query.

    Hey Google, set brightness to 65%.

    Ok Google, make it blue.

Next step

Register Custom Device Actions