Identifica y sincroniza

Una vez que crees una acción smart home, el siguiente paso es agregar funcionalidad en tu entrega para procesar los intents de casa inteligente y mostrar respuestas que Google Assistant reconozca.

Identifica al usuario

Assistant realiza solicitudes a la entrega de tu Acción smart home con el token de acceso que proporciona tu servidor de OAuth 2.0 en el encabezado Authorization.

POST /fulfillment HTTP/1.1
Host: smarthome.example.com
Content-Type: application/json
Authorization: Bearer ACCESS_TOKEN

Antes de responder a cualquier solicitud, la lógica de entrega debe verificar que esta credencial de token sea válida y determinar la cuenta de usuario asociada. Si el token de acceso no es válido, la entrega debería mostrar un error HTTP 401 Unauthorized.

Obtén una lista de los dispositivos y sus funciones

Herramientas recomendadas para esta tarea

Assistant envía un intent action.devices.SYNC a tu entrega para solicitar la lista de dispositivos asociados con un usuario determinado y sus capacidades. Tu entrega debe mostrar un ID único para cada usuario en el campo agentUserId de la respuesta SYNC. Este ID debe ser un valor inmutable para representar al usuario en tu servicio de nube. No se recomienda proporcionar direcciones de correo electrónico ni otros atributos basados en la configuración que el usuario puede cambiar.

El campo devices de tu respuesta de SYNC contiene todos los dispositivos a los que el usuario autorizó el acceso a Assistant, los tipos y traits que admiten, y los atributos necesarios para configurar el comportamiento de la característica en ese dispositivo específico.

El intent SYNC se activa durante la vinculación de la cuenta o cuando un usuario vuelve a sincronizar sus dispositivos de forma manual. Si cambia la lista de dispositivos, las características compatibles o los valores de los atributos de los usuarios, usa Solicitar sincronización para activar un intent SYNC nuevo e informar las actualizaciones a Google.

Solicitud
{
    "requestId": "ff36a3cc-ec34-11e6-b1a0-64510650abcf",
    "inputs": [{
      "intent": "action.devices.SYNC"
    }]
}
JSON
{
  "requestId": "ff36a3cc-ec34-11e6-b1a0-64510650abcf",
  "payload": {
    "agentUserId": "1836.15267389",
    "devices": [
      {
        "id": "123",
        "type": "action.devices.types.OUTLET",
        "traits": [
          "action.devices.traits.OnOff"
        ],
        "name": {
          "defaultNames": [
            "My Outlet 1234"
          ],
          "name": "Night light",
          "nicknames": [
            "wall plug"
          ]
        },
        "willReportState": false,
        "roomHint": "kitchen",
        "deviceInfo": {
          "manufacturer": "lights-out-inc",
          "model": "hs1234",
          "hwVersion": "3.2",
          "swVersion": "11.4"
        },
        "otherDeviceIds": [
          {
            "deviceId": "local-device-id"
          }
        ],
        "customData": {
          "fooValue": 74,
          "barValue": true,
          "bazValue": "foo"
        }
      },
      {
        "id": "456",
        "type": "action.devices.types.LIGHT",
        "traits": [
          "action.devices.traits.OnOff",
          "action.devices.traits.Brightness",
          "action.devices.traits.ColorSetting"
        ],
        "name": {
          "defaultNames": [
            "lights out inc. bulb A19 color hyperglow"
          ],
          "name": "lamp1",
          "nicknames": [
            "reading lamp"
          ]
        },
        "willReportState": false,
        "roomHint": "office",
        "attributes": {
          "colorModel": "rgb",
          "colorTemperatureRange": {
            "temperatureMinK": 2000,
            "temperatureMaxK": 9000
          },
          "commandOnlyColorSetting": false
        },
        "deviceInfo": {
          "manufacturer": "lights out inc.",
          "model": "hg11",
          "hwVersion": "1.2",
          "swVersion": "5.4"
        },
        "customData": {
          "fooValue": 12,
          "barValue": false,
          "bazValue": "bar"
        }
      }
    ]
  }
}
Node.js
const {smarthome} = require('actions-on-google');
const app = smarthome();
// ...
app.onSync((body, headers) => {
  // TODO Get devices for user
  return {
    requestId: body.requestId,
    payload: {
      agentUserId: "1836.15267389",
      devices: [{
        id: "123",
        type: "action.devices.types.OUTLET",
        traits: [
          "action.devices.traits.OnOff"
        ],
        name: {
          defaultNames: ["My Outlet 1234"],
          name: "Night light",
          nicknames: ["wall plug"]
        },
        willReportState: false,
        roomHint: "kitchen",
        deviceInfo: {
          manufacturer: "lights-out-inc",
          model: "hs1234",
          hwVersion: "3.2",
          swVersion: "11.4"
        },
        otherDeviceIds: [{
          deviceId: "local-device-id"
        }],
        customData: {
          fooValue: 74,
          barValue: true,
          bazValue: "foo"
        }
      }, {
        id: "456",
        type: "action.devices.types.LIGHT",
        traits: [
          "action.devices.traits.OnOff",
          "action.devices.traits.Brightness",
          "action.devices.traits.ColorSetting"
        ],
        name: {
          defaultNames: ["lights out inc. bulb A19 color hyperglow"],
          name: "lamp1",
          nicknames: ["reading lamp"]
        },
        willReportState: false,
        roomHint: "office",
        attributes: {
          colorModel: 'rgb',
          colorTemperatureRange: {
            temperatureMinK: 2000,
            temperatureMaxK: 9000
          },
          commandOnlyColorSetting: false
        },
        deviceInfo: {
          manufacturer: "lights out inc.",
          model: "hg11",
          hwVersion: "1.2",
          swVersion: "5.4"
        },
        customData: {
          fooValue: 12,
          barValue: false,
          bazValue: "bar"
        }
      }]
    }
  };
});
Java
@NotNull
@Override
public SyncResponse onSync(@NotNull SyncRequest syncRequest, @Nullable Map<?, ?> map) {
  Payload payload = new Payload();
  payload.setAgentUserId("1836.15267389");
  payload.setDevices(
      new Device[] {
        new Device.Builder()
            .setId("123")
            .setType("action.devices.types.OUTLET")
            .addTrait("action.devices.traits.OnOff")
            .setName(
                Collections.singletonList("My Outlet 1234"),
                "Night light",
                Collections.singletonList("Wall plug"))
            .setWillReportState(true)
            .setDeviceInfo("lights-out-inc", "hs1234", "3.2", "11.4")
            .setCustomData(
                new JSONObject()
                    .put("fooValue", 74)
                    .put("barValue", true)
                    .put("bazValue", "foo"))
            .build(),
        new Device.Builder()
            .setId("456")
            .setType("action.devices.types.LIGHT")
            .addTrait("action.devices.traits.OnOff")
            .addTrait("action.devices.traits.Brightness")
            .addTrait("action.devices.traits.ColorTemperature")
            .addTrait("action.devices.traits.ColorSpectrum")
            .setName(
                Collections.singletonList("Lights Out Inc. bulb A19 color hyperglow"),
                "Lamp",
                Collections.singletonList("Reading lamp"))
            .setWillReportState(true)
            .setDeviceInfo("Lights Out Inc.", "hg11", "1.2", "5.4")
            .setCustomData(
                new JSONObject()
                    .put("fooValue", 12)
                    .put("barValue", false)
                    .put("bazValue", "bar"))
            .build(),
      });
  return new SyncResponse(syncRequest.getRequestId(), payload);
}

Para obtener más información, consulta la documentación de referencia del intent SYNC.