diff --git a/README.md b/README.md index 080e3b1..6982f0a 100644 --- a/README.md +++ b/README.md @@ -331,6 +331,12 @@ controller of the engine that we're tracking the state of. Returns a boolean whether the engine supports the given command. +#### `async stateTracker.queueCommand(command)` + +- `command` [``](#command) + +Sends the given command to the engine after all ongoing syncs have finished. + #### `async stateTracker.sync(state)` - `state` [``](#enginestate) diff --git a/src/ControllerStateTracker.js b/src/ControllerStateTracker.js index 75cc050..56118fd 100644 --- a/src/ControllerStateTracker.js +++ b/src/ControllerStateTracker.js @@ -125,6 +125,16 @@ class ControllerStateTracker { return this._commands.includes(commandName) } + async queueCommand(...args) { + if (this.syncing) { + await new Promise(r => + this._syncFinishedEmitter.once('syncs-finished', r) + ) + } + + return this.controller.sendCommand(...args) + } + async _startProcessingSyncs() { if (this.syncing) return @@ -143,6 +153,7 @@ class ControllerStateTracker { } this.syncing = false + this._syncFinishedEmitter.emit('syncs-finished') } async _sync(state) { diff --git a/tests/ControllerStateTracker.test.js b/tests/ControllerStateTracker.test.js index c9e66c1..03a2c8c 100644 --- a/tests/ControllerStateTracker.test.js +++ b/tests/ControllerStateTracker.test.js @@ -130,6 +130,31 @@ t.test('sync history state', async t => { t.strictDeepEquals(stateTracker.state.history, commands) }) + t.test('queueCommand will send command after syncs are done', async t => { + let {stateTracker} = t.context + let commands = [ + {name: 'set_free_handicap', args: ['F4', 'G4', 'H4']}, + {name: 'play', args: ['B', 'D4']}, + {name: 'play', args: ['W', 'E4']} + ] + + let sentCommands = [] + + stateTracker.controller.on('command-sent', ({command}) => { + sentCommands.push(command) + }) + + let queuedCommand = {name: 'genmove', args: ['B']} + + await Promise.all([ + stateTracker.sync({history: commands}), + stateTracker.sync({history: commands}), + stateTracker.queueCommand(queuedCommand) + ]) + + t.strictDeepEquals(sentCommands.slice(-1)[0], queuedCommand) + }) + t.test('sync genmove commands', async t => { let {stateTracker} = t.context let history = []