前回はps4-wakerをセットアップしコマンド実行でPS4を制御しました。今回はプログラムからps4-wakerのライブラリを呼び出す方法の紹介と、IoT Hubからダイレクトメソッド呼び出しされてPS4を制御する部分の実装を行います。
※全体像および各関連記事へのリンクはこちらから
ps4-waker
ps4-wakeを使ってNode.jsからPS4を制御するコードは簡単です。スタンバイモードから復帰してNetflixを起動する場合は下記のようになります。ps4-wakerのメソッドはPromiseパターン(?)で実装されているのでコールバック地獄にならずにスラッと記述できます。
const Device = require("ps4-waker").Device; var ps4 = new Device(); ps4.turnOn() .then(() => startTitle('CUSA02988')) .then(() => ps4.close());
SmartHome Client
IoT Hubに接続してダイレクトメソッド呼び出しを受けたらPS4を制御するコードを実装します。ps4-wakerがPromiseパターンなのでIoT Hub ClientもBluebirdを使ってPromise化しています。またIoT Hubの接続文字列は環境変数「IOTHUB_CONNECTION_STRING」から取得するようにしています。
なおNode.js初心者なのでベストな実装かどうかは分かりません(´・ω・`)
"use strict"; const Bluebird = require("bluebird"); const Mqtt = require("azure-iot-device-mqtt").Mqtt; const Client = require("azure-iot-device").Client; const Device = require("ps4-waker").Device; const connectionString = process.env.IOTHUB_CONNECTION_STRING; const client = Bluebird.promisifyAll(Client.fromConnectionString(connectionString, Mqtt)); const onSendPS4Command = (request, response) => { console.log(request.payload); let command = request.payload.command; let titleId = request.payload.titleId; var res = Bluebird.promisifyAll(response); let ps4 = new Device({ bindAddress: process.argv[2] }); Promise.resolve() .then(() => command == "standby" ? ps4.turnOff() : ps4.turnOn()) .then(() => command == "start" ? ps4.startTitle(titleId) : null) .then(() => ps4.close()) .then(() => res.sendAsync(200, "success")) .catch(err => { console.error(err.toString()); res.sendAsync(500, err.toString()); }); }; client.openAsync() .then(() => { console.log("iot-hub client opened."); client.onDeviceMethod("sendPS4Command", onSendPS4Command); }) .catch(err => console.error(`could not open iot-hub client. ${err.toString()}`));
次回はGoogle Home(Assistant)からIoT Hub経由でダイレクトメソッドを呼び出す部分を実装します。