File size: 2,164 Bytes
0936134 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 | 'use strict';
let _ = require('lodash');
let log = require('./log');
let stateful = require('./stateful');
const proto = {
initialState: {
recognized: false,
noteBuffer: [],
playCount: 0,
recognizedCount: 0,
fireAction: false
},
notes: [],
noteThreshold: 150,
actionRepeats: null,
onNote(note, timestamp, timesRepeated, timesPlayed) {
let self = this;
let state = Object.assign({}, self.state);
let noteBuffer = state.noteBuffer;
let deleteIndex = 0;
noteBuffer = [...noteBuffer, { note, timestamp }];
for (let i = 0; i < noteBuffer.length; i++) {
if ((timestamp - noteBuffer[i].timestamp) > this.noteThreshold) {
deleteIndex++;
}
}
noteBuffer.splice(0, deleteIndex);
let notes;
if (self.notes.length > 0 && Array.isArray(self.notes[0])) {
notes = self.notes[timesRepeated];
} else {
notes = self.notes;
}
let justNotes = self.justNotes(noteBuffer);
log.debug("Recieved", JSON.stringify(justNotes));
let notesFound = self.contains(notes, justNotes);
if (notesFound) {
state.playCount++;
noteBuffer = [];
let repeats;
if (Array.isArray(self.repeats) && self.repeats.length > 0) {
repeats = self.repeats[timesRepeated];
} else {
repeats = self.repeats;
}
if (!repeats || state.playCount == repeats) {
log.debug('Sequence recognized');
if (typeof self.action === 'function') {
if (!self.actionRepeats || self.actionRepeats > timesRepeated) {
log.debug('Firing action')
self.action(timesRepeated, timesPlayed);
}
}
state.recognized = true;
}
}
self.state = Object.assign({}, state, { noteBuffer });
},
justNotes(array) {
let justNotes = [];
for (var i = 0; i < array.length; i++) {
justNotes.push(array[i].note);
}
return justNotes.sort();
},
contains(specifiedNotes, recievedNotes) {
return _.isEqual(_.intersection(specifiedNotes.sort(), recievedNotes.sort()), specifiedNotes.sort());
}
}
let sequence = function(config) {
return Object.assign({}, stateful(proto), config);
};
module.exports = sequence;
|