この記事は公開されてから1年以上経過しています。情報が古い可能性がありますので、ご注意ください。
本記事では、情報取得のためにAPIをコールしていますが、Alexa SDKでは、当該APIコールをラップするサービスが、既に提供されているとのご連絡を頂き、下記の更新記事を投稿させて頂きました。
1 はじめに
Alexaアプリでは、デバイスごとにタイムゾーンや単位(温度・距離)の設定ができるようになっています。
今回は、この設定内容をスキルで取得する要領を試してみました。
最初に、作成したサンプルを御覧ください。Alexaアプリで設定を変更すると、即座にそれをスキル側で取得できていることが分かります。
2 エンドポイント・デバイスID、アクセストークン
設定情報を取得するために必要なものは、エンドポイント、デバイスID、アクセストークンの3つです。そして、この3つは全てAlexaからのリクエストに含まれています。
{
"version": "1.0",
"session": {
....
},
"context": {
"System": {
"application": {
"applicationId": "xxx"
},
"user": {
"userId": "xxx"
},
"device": {
"deviceId": "xxxxxxxxxxxx",
"supportedInterfaces": {}
},
"apiEndpoint": "https://api.amazonalexa.com",
"apiAccessToken": "xxxxxxxxxxxx"
}
},
"request": {
....
}
}
リクエストJSONから各データを取得するコードは、下記のようになります。
const LaunchRequestHandler = {
canHandle(h) {
return isMatch(h,'LaunchRequest');
},
async handle(h) {
const context = h.requestEnvelope.context;
const apiEndpoint = context.System.apiEndpoint;
const accessToken = context.System.apiAccessToken;
const deviceId = context.System.device.deviceId;
取得したエンドポイントとデバイストークンを使用してURLを生成し、ヘッダにアクセストークンを入れてアクセスします。
GET {apiEndpoint}/v2/devices/{deviceId}/settings/System.timeZone
Authorization: Bearer accessToken
3 設定情報取得API
各種の情報は、次のURLで取得できます。
(1) タイムゾーン
/v2/devices/{deviceId}/settings/System.timeZone
返されるタイムゾーンの例は、以下のとおりです。
"Asia / Tokyo"
(2) 距離の単位
/v2/devices/{deviceId}/settings/System.distanceUnits
返される距離の単位の例は、以下のとおりです。
"METRIC" "IMPERIAL"
(3) 温度の単位
/v2/devices/{deviceId}/settings/System.temperatureUnit
返される温度の単位の例は、以下のとおりです。
"CELSIUS" "FAHRENHEIT"
4 実装
動作確認のために作成してみたコードです。
const LaunchRequestHandler = {
canHandle(h) {
return isMatch(h,'LaunchRequest');
},
async handle(h) {
const context = h.requestEnvelope.context;
const apiEndpoint = context.System.apiEndpoint;
const accessToken = context.System.apiAccessToken;
const deviceId = context.System.device.deviceId;
let timeZone = await get(apiEndpoint, deviceId, accessToken, 'System.timeZone');
let distanceUnits = await get(apiEndpoint, deviceId, accessToken, 'System.distanceUnits');
let temperatureUnit = await get(apiEndpoint, deviceId, accessToken, 'System.temperatureUnit');
console.log(timeZone + ' ' + distanceUnits + ' ' + temperatureUnit);
let message = '現在の設定です。<break time="1s"/>';
message += 'タイムゾーンは、' + timeZone;
message += '<break time="1s"/>';
message += '温度の単位は、';
message += (temperatureUnit == '"CELSIUS"') ? '摂氏' : '華氏';
message += '<break time="1s"/>';
message += '距離の単位は、';
message += (distanceUnits == '"METRIC"') ? 'メートル法' : 'インペリアル';
return h.responseBuilder
.speak(message)
.getResponse();
}
};
async function get(apiEndpoint, deviceId, accessToken, target) {
const opt = {
uri : apiEndpoint + '/v2/devices/' + deviceId + '/settings/' + target,
headers: {
'Authorization': 'Bearer ' + accessToken
}
}
return await rp(opt);
}
5 最後に
ユーザーが設定したタイムゾーンや単位をスキルの動作に反映させるのは、スキル開発者の役割です。もし、これらの設定に依存するスキルを作成する場合は、留意が必要でしょう。
6 参考リンク
Obtain Customer Settings Information with the Alexa Settings API