event cucle (#76)

* install sass
* refact: integration settings
- OSC in its own HTTP endpoint
- OSC settings have own object in db
* refact: simplify event cycle
* refact: restructure external triggers http
* refact: restructure external triggers osc+socket
* refact: restructure data updates
* feat: osc integration class
* IO improvements
- timer uses osc integration
- create trigger handler to manage external triggers
* refact: refract state machine update
* Integration: simple HTTP Client
* Integration: http options in datamodel
* Integration: call http send on life cycle
* feat/62-logging: fix issue #71
This commit is contained in:
Carlos Valente
2021-12-22 18:17:48 +01:00
committed by GitHub
parent 2b2bafa8c6
commit ac0d5832b6
53 changed files with 2041 additions and 1948 deletions
+429 -212
View File
@@ -1,6 +1,9 @@
import { Timer } from './Timer.js';
import { Server } from 'socket.io';
import {DAYMS, getSelectionByRoll} from './classUtils.js';
import {Timer} from './Timer.js';
import {Server} from 'socket.io';
import {DAY_TO_MS, getSelectionByRoll, replacePlaceholder, updateRoll} from './classUtils.js';
import {OSCIntegration} from './integrations/Osc.js';
import {HTTPIntegration} from "./integrations/Http.js";
import {cleanURL} from "../utils/url.js";
/*
* EventTimer adds functions specific to APP
@@ -11,11 +14,35 @@ import {DAYMS, getSelectionByRoll} from './classUtils.js';
*/
export class EventTimer extends Timer {
// Keep track of Timer lifecycle
// idle: before it is initialised
// load: when a new event is loaded
// update: every update call cycle (1 x second)
// stop: when the timer is stopped
// finish: when a timer finishes
cycleState = {
idle: 'idle',
onLoad: 'onLoad',
armed: 'armed',
onStart: 'onStart',
onUpdate: 'onUpdate',
onPause: 'onPause',
onStop: 'onStop',
onFinish: 'onFinish',
};
ontimeCycle = 'idle';
prevCycle = null;
lastUpdate = null;
// Socket IO Object
io = null;
// OSC Client
oscClient = null;
// OSC Object
osc = null;
// HTTP Client Object
http = null;
_numClients = 0;
_interval = null;
@@ -62,10 +89,21 @@ export class EventTimer extends Timer {
_eventlist = null;
onAir = false;
constructor(httpServer, oscClient, config) {
/**
* Instantiates an event timer object
* @param httpServer
* @param timerConfig
* @param [oscConfig]
* @param [httpConfig]
*/
constructor(httpServer, timerConfig, oscConfig, httpConfig) {
// call super constructor
super();
// initialise class variables
this.numEvents = 0;
// initialise socketIO server
this.io = new Server(httpServer, {
cors: {
@@ -76,135 +114,47 @@ export class EventTimer extends Timer {
},
});
// Todo: extract
// initialise osc object
if (oscConfig != null) {
console.log('initialise OSC Client on port: ', oscConfig?.port);
this.osc = new OSCIntegration();
this.osc.init(oscConfig);
}
// Todo: extract
// initialise http object
if (httpConfig != null) {
this.http = new HTTPIntegration();
this.http.init(httpConfig);
this.httpMessages = httpConfig.messages;
}
// set recurrent emits
this._interval = setInterval(
() => this.broadcastTimer(),
config.timer.refresh
() => this.runCycle(),
timerConfig?.refresh || 1000
);
// listen to new connections
this._listenToConnections();
// set oscClient
this.updateOSCClient(oscClient);
}
/**
* @description Updates the osc client used in the object
* @param {object} oscClient
*/
updateOSCClient(oscClient) {
this.oscClient = oscClient;
}
/**
* @description Sends osc value from predefined messages
* @param {string} event - message to be sent
*/
sendOSC(event) {
if (this.oscClient == null) return;
const add = '/ontime';
const play = 'play';
const pause = 'pause';
const stop = 'stop';
const prev = 'prev';
const next = 'next';
const reload = 'reload';
const finished = 'finished';
const time = this.timeTag;
const overtime = this.current > 0 ? 0 : 1;
const title = this.titles?.titleNow || '';
const presenter = this.titles?.presenterNow || '';
switch (event) {
case 'time':
// Send Timetag Message
this.oscClient.send(add + '/time', time, (err) => {
if (err) console.error(err);
});
break;
case 'finished':
// Runs when timer reaches 0
this.oscClient.send(add, finished, (err) => {
if (err) console.error(err);
});
break;
case 'overtime':
// Whether timer is negative
this.oscClient.send(add + '/overtime', overtime, (err) => {
if (err) console.error(err);
});
break;
case 'titles':
// Send Title of current event
this.oscClient.send(add + '/title', title, (err) => {
if (err) console.error(err);
});
// Send presenter data on current event
this.oscClient.send(add + '/presenter', presenter, (err) => {
if (err) console.error(err);
});
break;
case 'play':
// Play Message
this.oscClient.send(add, play, (err) => {
if (err) console.error(err);
});
break;
case 'pause':
// Pause Message
this.oscClient.send(add, pause, (err) => {
if (err) console.error(err);
});
break;
case 'stop':
// Stop Message
this.oscClient.send(add, stop, (err) => {
if (err) console.error(err);
});
break;
case 'prev':
this.oscClient.send(add, prev, (err) => {
if (err) console.error(err);
});
break;
case 'next':
this.oscClient.send(add, next, (err) => {
if (err) console.error(err);
});
break;
case 'reload':
this.oscClient.send(add, reload, (err) => {
if (err) console.error(err);
});
break;
default:
break;
}
}
/**
* @description Shutdown process
*/
shutdown() {
console.log('Closing socket server');
console.log('Shutting down integrations')
console.log('... Closing socket server');
this.io.close();
console.log('... Closing osc server');
this.osc.shutdown();
}
// send current timer
broadcastTimer() {
// through websockets
this.io.emit('timer', this.getTimes());
// through OSC, only if running
if (this.state === 'start' || this.state === 'roll') {
this.sendOSC('time');
this.sendOSC('overtime');
this.sendOSC('titles');
}
}
// broadcast state
@@ -230,11 +180,239 @@ export class EventTimer extends Timer {
this.io.emit(address, payload);
}
/**
* @description Interface for triggering playback actions
* @param {string} action - state to be triggered
* @returns {boolean} Whether action was called
*/
trigger(action) {
// Todo: reply should come from status change
let reply = true;
switch (action) {
case 'start':
if (this.numEvents === 0 || this.numEvents == null) return false;
// Call action and force update
this.start();
this.runCycle();
break;
case 'pause':
if (this.numEvents === 0 || this.numEvents == null) return false;
// Call action and force update
this.pause();
this.runCycle();
break;
case 'stop':
if (this.numEvents === 0 || this.numEvents == null) return false;
// Call action and force update
this.stop();
this.runCycle();
break;
case 'roll':
if (this.numEvents === 0 || this.numEvents == null) return false;
// Call action and force update
this.roll();
this.runCycle();
break;
case 'previous':
if (this.numEvents === 0 || this.numEvents == null) return false;
// Call action and force update
this.previous();
this.runCycle();
break;
case 'next':
if (this.numEvents === 0 || this.numEvents == null) return false;
// Call action and force update
this.next();
this.runCycle();
break;
case 'unload':
if (this.numEvents === 0 || this.numEvents == null) return false;
// Call action and force update
this.unload();
this.runCycle();
break;
case 'reload':
if (this.numEvents === 0 || this.numEvents == null) return false;
// Call action and force update
this.reload();
this.runCycle();
break;
case 'onAir':
// Call action
this.setonAir(true);
break;
case 'offAir':
// Call action and force update
this.setonAir(false);
break;
default:
// Error, disable flag
console.log('ERROR: Unhandled action triggered')
reply = false;
break;
}
return reply;
}
/**
* @description State machine checks what actions need to
* happen at every app cycle
*/
runCycle() {
const h = this.httpMessages?.messages;
let httpMessage = null;
switch (this.ontimeCycle) {
case "idle":
break;
case "armed":
// if we come from roll, see if we can start
if (this.state === 'roll') {
this.update();
}
break;
case "onLoad":
// broadcast change
this.broadcastState();
// check integrations - http
if (h?.onLoad?.enabled) {
if (h?.onLoad?.url != null || h?.onLoad?.url !== '') {
httpMessage = h?.onLoad?.url;
}
}
// update lifecycle: armed
this.ontimeCycle = this.cycleState.armed;
break;
case "onStart":
// broadcast current state
this.broadcastState();
// send OSC if there is something running
// _finish at is only set when an event is loaded
if (this._finishAt > 0) {
this.osc.send(this.osc.implemented.play);
}
// check integrations - http
if (h?.onLoad?.enabled) {
if (h?.onLoad?.url != null || h?.onStart?.url !== '') {
httpMessage = h?.onStart?.url;
}
}
// update lifecycle: onUpdate
this.ontimeCycle = this.cycleState.onUpdate;
break;
case "onUpdate":
// call update
this.update();
// broadcast current state
this.broadcastTimer();
// through OSC, only if running
if (this.state === 'start' || this.state === 'roll') {
if (this.current != null && this.secondaryTimer == null) {
this.osc.send(this.osc.implemented.time, this.timeTag);
this.osc.send(this.osc.implemented.overtime, this.current > 0 ? 0 : 1);
this.osc.send(this.osc.implemented.title, this.titles?.titleNow || '');
}
}
// check integrations - http
if (h?.onLoad?.enabled) {
if (h?.onLoad?.url != null || h?.onUpdate?.url !== '') {
httpMessage = h?.onUpdate?.url;
}
}
break;
case "onPause":
// broadcast current state
this.broadcastState();
// send OSC
this.osc.send(this.osc.implemented.pause);
// check integrations - http
if (h?.onLoad?.enabled) {
if (h?.onLoad?.url != null || h?.onPause?.url !== '') {
httpMessage = h?.onPause?.url;
}
}
// update lifecycle: armed
this.ontimeCycle = this.cycleState.armed;
break;
case "onStop":
// broadcast change
this.broadcastState();
// send OSC if something was actually stopped
if (this.prevCycle === this.cycleState.onUpdate) {
this.osc.send(this.osc.implemented.stop);
}
// check integrations - http
if (h?.onLoad?.enabled) {
if (h?.onLoad?.url != null || h?.onStop?.url !== '') {
httpMessage = h?.onStop?.url;
}
}
// update lifecycle: idle
this.ontimeCycle = this.cycleState.idle;
break;
case "onFinish":
console.log('onFinish')
// broadcast change
this.broadcastState(false);
// finished an event
this.osc.send(this.osc.implemented.finished);
// check integrations - http
if (h?.onLoad?.enabled) {
if (h?.onLoad?.url != null || h?.onFinish?.url !== '') {
httpMessage = h?.onFinish?.url;
}
}
// update lifecycle: onUpdate
this.ontimeCycle = this.cycleState.onUpdate;
break;
default:
console.log(`ERROR: Unhandled cycle: ${this.ontimeCycle}`)
}
// send http message if any
if (httpMessage != null) {
const v = {
'$timer': this.timeTag,
'$title': this.titles.titleNow,
'$presenter': this.titles.presenterNow,
'$subtitle': this.titles.subtitleNow,
'$next-title': this.titles.titleNext,
'$next-presenter': this.titles.presenterNext,
'$next-subtitle': this.titles.subtitleNext,
}
const m = cleanURL(replacePlaceholder(httpMessage, v));
this.http.send(m);
}
// update
this.update();
// reset cycle
this.prevCycle = this.ontimeCycle;
}
update() {
// if there is nothing selected, update clock
const now = this._getCurrentTime();
// if there is nothing selected, update only clock
if (this.selectedEventId == null && this.state !== 'roll') {
// if we are not updating, send the timers
if (this.ontimeCycle !== this.cycleState.onUpdate) {
this.clock = now;
this.broadcastThis('timer', {
clock: now,
@@ -244,81 +422,59 @@ export class EventTimer extends Timer {
expectedFinish: this._getExpectedFinish(),
startedAt: this._startedAt,
});
return;
}
// only implement roll here
if (this.state !== 'roll') {
super.update();
} else {
// update timer as usual
this.clock = now;
if (this.selectedEventId && this.current > 0) {
// something is running, update
this.current = this._finishAt - now;
} else if (this.secondaryTimer > 0) {
// waiting to start, update secondary
this.secondaryTimer = this._secondaryTarget - now;
// Have we skipped onStart?
if (this.state === 'start' || this.state === 'roll') {
if (this.ontimeCycle === this.cycleState.armed) {
// update lifecycle: onStart
this.ontimeCycle = this.cycleState.onStart;
this.runCycle();
}
}
// update default functions
super.update();
if (this._finishedFlag) {
// update lifecycle: onFinish and call cycle
this.ontimeCycle = this.cycleState.onFinish;
this._finishedFlag = false;
this.runCycle();
}
// only implement roll here, rest implemented in super
if (this.state === 'roll') {
const u = {
selectedEventId: this.selectedEventId,
current: this.current,
// safeguard on midnight rollover
_finishAt: this._finishAt >= this._startedAt ? this._finishAt : this._finishAt + DAY_TO_MS,
clock: this.clock,
secondaryTimer: this.secondaryTimer,
_secondaryTarget: this._secondaryTarget,
}
// look for event if none is loaded
const currentRunning = this.current <= 0 && this.current !== null;
const secondaryRunning =
this.secondaryTimer <= 0 && this.secondaryTimer !== null;
const {updatedTimer, updatedSecondaryTimer, doRollLoad, isFinished} = updateRoll(u);
if (currentRunning) {
// finished an event
this.sendOSC('finished');
this._finishedFlag = true;
this.current = updatedTimer;
this.secondaryTimer = updatedSecondaryTimer;
if (isFinished) {
// update lifecycle: onFinish
this.ontimeCycle = this.cycleState.onFinish;
this.runCycle();
}
if (currentRunning || secondaryRunning) {
// look for events
if (doRollLoad) {
this.rollLoad();
// broadcast state without recalculating timer
this.broadcastState(false);
}
}
// if event is finished
if (
this.current <= 0 &&
(this.state === 'start' || this.state === 'roll') &&
!this._finishedFlag
) {
if (this._finishedAt === null) {
this._finishedAt = now;
}
this.sendOSC('finished');
this._finishedFlag = true;
}
}
_setterManager(action, payload) {
switch (action) {
/*******************************************/
// playstate
case 'set-playstate':
// check state is defined
if (payload === 'start') this.start();
else if (payload === 'pause') this.pause();
else if (payload === 'stop') this.stop();
else if (payload === 'previous') this.previous();
else if (payload === 'next') this.next();
else if (payload === 'reload') this.reload();
else if (payload === 'unload') this.unload();
else if (payload === 'roll') this.roll();
// TODO: Cleanup
// here tdo this.broadcastState;
// remove broadcast from functions
this.broadcastThis('playstate', this.state);
this.broadcastThis('selected-id', this.selectedEventId);
this.broadcastThis('titles', this.titles);
break;
/*******************************************/
// Presenter message
case 'set-presenter-text':
@@ -423,7 +579,7 @@ export class EventTimer extends Timer {
/*******************************************/
// playstate
socket.on('set-playstate', (data) => {
this._setterManager('set-playstate', data);
this.trigger(data);
});
socket.on('get-playstate', () => {
@@ -453,6 +609,10 @@ export class EventTimer extends Timer {
socket.emit('selected-id', this.selectedEventId);
});
socket.on('get-numevents', () => {
socket.emit('numevents', this.numEvents);
});
socket.on('get-next-id', () => {
socket.emit('next-id', this.nextEventId);
});
@@ -539,8 +699,11 @@ export class EventTimer extends Timer {
this._eventlist = [];
this.numEvents = 0;
// broadcast change
this.broadcastState();
// update lifecycle: onStop
this.ontimeCycle = this.cycleState.onStop;
// update clients
this.broadcastThis('numevents', this.numEvents);
}
setupWithEventList(eventlist) {
@@ -559,6 +722,12 @@ export class EventTimer extends Timer {
// load first event
this.loadEvent(0);
// update clients
this.broadcastThis('numevents', this.numEvents);
// run cycle
this.runCycle();
}
updateEventList(eventlist) {
@@ -601,7 +770,11 @@ export class EventTimer extends Timer {
this.loadEvent(eventIndex, type);
}
this.broadcastState();
// update clients
this.broadcastThis('numevents', this.numEvents);
// run cycle
this.runCycle();
}
updateSingleEvent(id, entry) {
@@ -640,7 +813,11 @@ export class EventTimer extends Timer {
console.log(error);
}
this.broadcastState();
// update clients
this.broadcastThis('numevents', this.numEvents);
// run cycle
this.runCycle();
}
deleteId(eventId) {
@@ -670,37 +847,53 @@ export class EventTimer extends Timer {
this._loadTitlesNow();
}
this.broadcastState();
// update clients
this.broadcastThis('numevents', this.numEvents);
// run cycle
this.runCycle();
}
/**
* @description loads an event with a given Id
* @param eventId - ID of event in eventlist
*/
loadEventById(eventId) {
const eventIndex = this._eventlist.findIndex((e) => e.id === eventId);
if (eventIndex === -1) return;
this.pause();
this.loadEvent(eventIndex, 'load', true);
// run cycle
this.runCycle();
}
/**
* @description loads an event with a given index
* @param eventIndex - Index of event in eventlist
*/
loadEventByIndex(eventIndex) {
if (eventIndex === -1 || eventIndex > this.numEvents) return;
this.pause();
this.loadEvent(eventIndex, 'load', true);
// run cycle
this.runCycle();
}
// Loads a given event
// load timers
// load selectedEventIndex
// load titles
loadEvent(eventIndex, type = 'load', broadcastChange = 'false') {
loadEvent(eventIndex, type = 'load') {
const e = this._eventlist[eventIndex];
if (e == null) return;
const start = e.timeStart == null || e.timeStart === '' ? 0 : e.timeStart;
let end = e.timeEnd == null || e.timeEnd === '' ? 0 : e.timeEnd;
// in case the end is earlier than start, we assume is the day after
if (end < start) end += DAYMS;
if (end < start) end += DAY_TO_MS;
// time stuff changes on wheter we keep the running clock
// time stuff changes on whether we keep the running clock
if (type === 'load') {
this._resetTimers();
@@ -724,9 +917,8 @@ export class EventTimer extends Timer {
// look for event after
this._loadTitlesNext();
if (broadcastChange)
// broadcast current state
this.broadcastState();
// update lifecycle: onLoad
this.ontimeCycle = this.cycleState.onLoad;
}
_loadTitlesNow() {
@@ -980,54 +1172,55 @@ export class EventTimer extends Timer {
}
start() {
// do we need to change
if (this.state === 'start') return;
// if there is nothing selected, no nothing
if (this.selectedEventId == null) return;
// call super
super.start();
// broadcast current state
this.broadcastState();
// send OSC
this.sendOSC('play');
// update lifecycle: onStart
this.ontimeCycle = this.cycleState.onStart;
}
pause() {
// do we need to change
if (this.state === 'pause') return;
// if there is nothing selected, no nothing
if (this.selectedEventId == null) return;
// call super
super.pause();
// broadcast current state
this.broadcastState();
// send OSC
this.sendOSC('pause');
// update lifecycle: onPause
this.ontimeCycle = this.cycleState.onPause;
}
stop() {
// do we need to change
if (this.state === 'stop') return;
// call super
super.stop();
// broadcast current state
this.broadcastState();
// send OSC
this.sendOSC('stop');
// update lifecycle: onPause
this.ontimeCycle = this.cycleState.onStop;
}
increment(amount) {
// call super
super.increment(amount);
// broadcast current state
this.broadcastState();
// run cycle
this.runCycle();
}
rollLoad() {
const now = this._getCurrentTime();
let prevLoaded = this.selectedEventId;
// maybe roll has already been loaded
if (this.secondaryTimer === null) {
@@ -1103,18 +1296,31 @@ export class EventTimer extends Timer {
if (publicIndex !== null) {
this._loadThisTitles(this._eventlist[publicIndex], 'now-public');
}
if (prevLoaded !== this.selectedEventId) {
// update lifecycle: onLoad
this.ontimeCycle = this.cycleState.onLoad;
// ensure we go through onLoad cycle
this.runCycle();
}
}
roll() {
// do we need to change
if (this.state === 'roll') return;
if (this.numEvents === 0 || this.numEvents == null) return;
// set state
this.state = 'roll';
// update lifecycle: armed
this.ontimeCycle = this.cycleState.armed;
// load into event
this.rollLoad();
// broadcast change
this.broadcastState();
}
@@ -1122,6 +1328,9 @@ export class EventTimer extends Timer {
// check that we have events to run
if (this.numEvents < 1) return;
// maybe this is the first event?
if (this.selectedEventIndex === 0) return;
// if there is no event running, go to first
if (this.selectedEventIndex == null) {
this.loadEvent(0);
@@ -1129,7 +1338,7 @@ export class EventTimer extends Timer {
}
// send OSC
this.sendOSC('prev');
this.osc.send(this.osc.implemented.previous);
// change playstate
this.pause();
@@ -1145,6 +1354,9 @@ export class EventTimer extends Timer {
// check that we have events to run
if (this.numEvents < 1) return;
// maybe this is the last event?
if (this.selectedEventIndex === this.numEvents - 1) return;
// if there is no event running, go to first
if (this.selectedEventIndex == null) {
this.loadEvent(0);
@@ -1152,7 +1364,7 @@ export class EventTimer extends Timer {
}
// send OSC
this.sendOSC('next');
this.osc.send(this.osc.implemented.next);
// change playstate
this.pause();
@@ -1173,16 +1385,21 @@ export class EventTimer extends Timer {
// reset selected
this._resetSelection();
// broadcast state
this.broadcastState();
// reset playstate
this.stop();
}
reload() {
// reset playstate
if (this.numEvents === 0 || this.numEvents == null) return;
// change playstate
this.pause();
// send OSC
this.sendOSC('reload');
this.osc.send(this.osc.implemented.reload);
// reload data
this.loadEvent(this.selectedEventIndex);
+46 -11
View File
@@ -24,11 +24,35 @@ export class Timer {
constructor() {}
// call setup separately
setupWithSeconds(seconds, autoStart = false) {
// aux
const now = this._getCurrentTime();
this.clock = now;
// populate targets
this.duration = seconds * 1000;
this._finishAt = now + seconds * 1000;
// start counting
this._startedAt = now;
if (autoStart) {
this.state = 'start';
} else {
this._pausedAt = now;
this._pausedInterval = 0;
}
this._pausedTotal = 0;
this.update();
}
// update()
update() {
// get current time
const now = this._getCurrentTime();
this.clock = now;
let checkFinish = false;
// check playstate
switch (this.state) {
@@ -40,6 +64,8 @@ export class Timer {
this.current =
this._startedAt + this.duration + this._pausedTotal - now;
// enable flag
checkFinish = true;
break;
case 'pause':
// update paused time
@@ -48,28 +74,37 @@ export class Timer {
if (this._startedAt != null) {
// update current timer
this.current =
this._startedAt +
this.duration +
this._pausedTotal +
this._pausedInterval -
now;
this._startedAt
+ this.duration
+ this._pausedTotal
+ this._pausedInterval
- now;
}
// enable flag
checkFinish = true;
break;
case 'stop':
// nothing here yet
break;
default:
console.error('Timer: no playstate on update call', this.state);
break;
}
if (checkFinish) {
// is event finished?
const isTimeOver = this.current <= 0;
const isUpdating = (this.state !== 'pause');
if (isTimeOver && isUpdating && this._finishedAt == null) {
if (this._finishedAt === null) this._finishedAt = now;
this._finishedFlag = true;
}
}
}
// helpers
static toSeconds(millis) {
if (millis == null) return null;
return Math.ceil(millis * 0.001);
}
// get current time in epoc
@@ -148,7 +183,7 @@ export class Timer {
// do we need to change
if (this.state === 'start') return;
else if (this._startedAt == null) {
// it hasnt started yet
// it hasn't started yet
const now = this._getCurrentTime();
// set start time as now
this._startedAt = now;
+187 -28
View File
@@ -1,22 +1,29 @@
import {DAYMS, getSelectionByRoll, normaliseEndTime, sortArrayByProperty} from '../classUtils.js';
import {
DAY_TO_MS,
getSelectionByRoll,
replacePlaceholder,
normaliseEndTime,
sortArrayByProperty,
updateRoll
} from '../classUtils.js';
// test sortArrayByProperty()
describe('sort simple arrays of objects', () => {
it('sort array 1-5', () => {
const arr1 = [
{ timeStart: 1 },
{ timeStart: 5 },
{ timeStart: 3 },
{ timeStart: 2 },
{ timeStart: 4 },
{timeStart: 1},
{timeStart: 5},
{timeStart: 3},
{timeStart: 2},
{timeStart: 4},
];
const arr1Expected = [
{ timeStart: 1 },
{ timeStart: 2 },
{ timeStart: 3 },
{ timeStart: 4 },
{ timeStart: 5 },
{timeStart: 1},
{timeStart: 2},
{timeStart: 3},
{timeStart: 4},
{timeStart: 5},
];
const sorted = sortArrayByProperty(arr1, 'timeStart');
@@ -25,21 +32,21 @@ describe('sort simple arrays of objects', () => {
it('sort array 1-5 with null', () => {
const arr1 = [
{ timeStart: 1 },
{ timeStart: 5 },
{ timeStart: 3 },
{ timeStart: 2 },
{ timeStart: 4 },
{ timeStart: null },
{timeStart: 1},
{timeStart: 5},
{timeStart: 3},
{timeStart: 2},
{timeStart: 4},
{timeStart: null},
];
const arr1Expected = [
{ timeStart: null },
{ timeStart: 1 },
{ timeStart: 2 },
{ timeStart: 3 },
{ timeStart: 4 },
{ timeStart: 5 },
{timeStart: null},
{timeStart: 1},
{timeStart: 2},
{timeStart: 3},
{timeStart: 4},
{timeStart: 5},
];
const sorted = sortArrayByProperty(arr1, 'timeStart');
@@ -244,7 +251,6 @@ describe('test that roll loads selection in right order', () => {
});
// test getSelectionByRoll()
describe('test that roll behaviour with overlapping times', () => {
const eventlist = [
{
@@ -384,6 +390,68 @@ describe('test that roll behaviour with overlapping times', () => {
});
});
// test replacePlaceholder()
describe('test that it replaces data correctly', () => {
const values = {
$timer: "timer",
$title: "title",
$presenter: "presenter",
$subtitle: "subtitle",
"$next-title": "next title",
"$next-presenter": "next presenter",
"$next-subtitle": "next subtitle"
};
it('replaces timer', () => {
const test = '___1232132 $timer';
const expected = '___1232132 timer';
const s = replacePlaceholder(test, values)
expect(s).toBe(expected);
});
it('replaces title', () => {
const test = '___1232132 $title';
const expected = '___1232132 title';
const s = replacePlaceholder(test, values)
expect(s).toBe(expected);
});
it('replaces presenter', () => {
const test = '___1232132 $presenter';
const expected = '___1232132 presenter';
const s = replacePlaceholder(test, values)
expect(s).toBe(expected);
});
it('replaces subtitle', () => {
const test = '___1232132 $subtitle';
const expected = '___1232132 subtitle';
const s = replacePlaceholder(test, values)
expect(s).toBe(expected);
});
it('replaces next next title', () => {
const test = '___1232132 $next-title';
const expected = '___1232132 next title';
const s = replacePlaceholder(test, values)
expect(s).toBe(expected);
});
it('replaces next presenter', () => {
const test = '___1232132 $next-presenter';
const expected = '___1232132 next presenter';
const s = replacePlaceholder(test, values)
expect(s).toBe(expected);
});
it('replaces next subtitle', () => {
const test = '___1232132 $next-subtitle';
const expected = '___1232132 next subtitle';
const s = replacePlaceholder(test, values)
expect(s).toBe(expected);
});
});
// test getSelectionByRoll() on issue #58
describe('test that roll behaviour multi day event edge cases', () => {
@@ -407,8 +475,8 @@ describe('test that roll behaviour multi day event edge cases', () => {
timers: {
_startedAt: eventlist[0].timeStart,
_finishAt: eventlist[0].timeEnd,
current: eventlist[0].timeEnd + DAYMS - now,
duration: DAYMS - eventlist[0].timeStart + eventlist[0].timeEnd,
current: eventlist[0].timeEnd + DAY_TO_MS - now,
duration: DAY_TO_MS - eventlist[0].timeStart + eventlist[0].timeEnd,
},
timeToNext: null,
};
@@ -454,10 +522,10 @@ test('test typical scenarios', () => {
expect(normaliseEndTime(t1.start, t1.end)).toBe(t1_expected);
const t2 = {
start: 10+DAYMS,
start: 10 + DAY_TO_MS,
end: 20,
}
const t2_expected = 20+DAYMS;
const t2_expected = 20 + DAY_TO_MS;
expect(normaliseEndTime(t2.start, t2.end)).toBe(t2_expected);
@@ -470,3 +538,94 @@ test('test typical scenarios', () => {
expect(normaliseEndTime(t3.start, t3.end)).toBe(t3_expected);
});
// test updateRoll()
describe('typical scenarios', () => {
it('it updates running events correctly', () => {
const timers = {
selectedEventId: 1,
current: 10,
_finishAt: 15,
clock: 11,
secondaryTimer: null,
_secondaryTarget: null,
};
const expected = {
updatedTimer: timers._finishAt - timers.clock,
updatedSecondaryTimer: null,
doRollLoad: false,
isFinished: false,
};
expect(updateRoll(timers)).toStrictEqual(expected);
// test that it can jump time
timers._finishAt = 1000;
timers.clock = 600;
expected.updatedTimer = timers._finishAt - timers.clock;
expect(updateRoll(timers)).toStrictEqual(expected);
});
it('it updates secondary timer', () => {
const timers = {
selectedEventId: null,
current: null,
_finishAt: null,
clock: 11,
secondaryTimer: 1,
_secondaryTarget: 15,
};
const expected = {
updatedTimer: null,
updatedSecondaryTimer: timers._secondaryTarget - timers.clock,
doRollLoad: false,
isFinished: false,
};
expect(updateRoll(timers)).toStrictEqual(expected);
});
it('flags an event end', () => {
const timers = {
selectedEventId: 1,
current: 10,
_finishAt: 11,
clock: 12,
secondaryTimer: null,
_secondaryTarget: null,
};
const expected = {
updatedTimer: timers._finishAt - timers.clock,
updatedSecondaryTimer: null,
doRollLoad: true,
isFinished: true,
};
expect(updateRoll(timers)).toStrictEqual(expected);
});
it('secondary events do not trigger event ends', () => {
const timers = {
selectedEventId: null,
current: null,
_finishAt: null,
clock: 16,
secondaryTimer: 1,
_secondaryTarget: 15,
};
const expected = {
updatedTimer: null,
updatedSecondaryTimer: timers._secondaryTarget - timers.clock,
doRollLoad: true,
isFinished: false,
};
expect(updateRoll(timers)).toStrictEqual(expected);
});
});
@@ -0,0 +1,137 @@
import {EventTimer} from "../EventTimer";
import http from 'http';
import express from "express";
// Create server
const app = express();
const server = http.createServer(app);
// necessary config
const timerConfig = {refresh: 1000};
beforeEach(async () => {
server.listen(0, '0.0.0.0');
});
afterEach(async () => {
await server.close();
});
test('object instantiates correctly', async () => {
const t = new EventTimer(server, timerConfig);
// it contains everything from Timer
expect(t.clock).toBeNull();
expect(t.duration).toBeNull();
expect(t.current).toBeNull();
expect(t.timeTag).toBeNull();
expect(t.secondaryTimer).toBeNull();
expect(t._secondaryTarget).toBeNull();
expect(t._finishAt).toBeNull();
expect(t._finishedAt).toBeNull();
expect(t._finishedFlag).toBeFalsy();
expect(t._startedAt).toBeNull();
expect(t._pausedAt).toBeNull();
expect(t._pausedInterval).toBeNull();
expect(t._pausedTotal).toBeNull();
expect(t.state).toBe('stop');
// and its own properties
expect(t.ontimeCycle).toBe('idle');
expect(t.prevCycle).toBeNull();
expect(t.lastUpdate).toBeNull();
expect(t.io).not.toBeNull();
expect(t.osc).toBeNull();
expect(t.http).toBeNull();
expect(t._numClients).toBe(0);
expect(t._interval).not.toBeNull();
expect(t.presenter).toStrictEqual({text: '', visible: false});
expect(t.public).toStrictEqual({text: '', visible: false});
expect(t.lower).toStrictEqual({text: '', visible: false});
expect(t.lower).toStrictEqual({text: '', visible: false});
const expectTitlesPublic = {
titleNow: null,
subtitleNow: null,
presenterNow: null,
titleNext: null,
subtitleNext: null,
presenterNext: null,
};
const expectTitles = {
...expectTitlesPublic,
noteNow: null,
noteNext: null,
};
expect(t.titlesPublic).toStrictEqual(expectTitlesPublic);
expect(t.titles).toStrictEqual(expectTitles);
expect(t.selectedEventIndex).toBeNull();
expect(t.selectedEventId).toBeNull();
expect(t.nextEventId).toBeNull();
expect(t.selectedPublicEventId).toBeNull();
expect(t.nextPublicEventId).toBeNull();
expect(t.numEvents).toBe(0);
expect(t._eventlist).toBeNull();
expect(t.onAir).toBeFalsy();
});
describe('test triggers behaviour', () => {
const t = new EventTimer(server, timerConfig);
it('ignores bad commands', () => {
const success = t.trigger('test');
expect(success).toBeFalsy();
})
it('does not allow triggering events with an empty list', () => {
expect(t.numEvents).toBe(0);
expect(t.trigger('start')).toBeFalsy();
expect(t.trigger('pause')).toBeFalsy();
expect(t.trigger('stop')).toBeFalsy();
expect(t.trigger('roll')).toBeFalsy();
expect(t.trigger('previous')).toBeFalsy();
expect(t.trigger('next')).toBeFalsy();
expect(t.trigger('reload')).toBeFalsy();
expect(t.onAir).toBeFalsy();
expect(t.trigger('onAir')).toBeTruthy();
expect(t.onAir).toBeTruthy();
expect(t.trigger('offAir')).toBeTruthy();
expect(t.onAir).toBeFalsy();
});
it('...and is consistent by calling the class methods', () => {
expect(t.numEvents).toBe(0);
expect(t.state).toBe('stop');
t.start();
expect(t.state).toBe('stop');
t.pause();
expect(t.state).toBe('stop');
t.stop();
expect(t.state).toBe('stop');
t.roll();
expect(t.state).toBe('stop');
t.previous();
expect(t.state).toBe('stop');
t.next();
expect(t.state).toBe('stop');
t.reload();
expect(t.state).toBe('stop');
});
})
+81 -6
View File
@@ -1,13 +1,17 @@
export const DAYMS = 86400000;
/**
* Utility variable: 24 hour in milliseconds .
* @type {number}
*/
export const DAY_TO_MS = 86400000;
/**
* @description handle events that span over midnight
* @param {num} start - When does the event start
* @param {num} end - When does the event end
* @returns {num} normalised time
* @param {number} start - When does the event start
* @param {number} end - When does the event end
* @returns {number} normalised time
*/
export const normaliseEndTime = (start, end) => (end < start ? end + DAYMS : end);
export const normaliseEndTime = (start, end) => (end < start ? end + DAY_TO_MS : end);
/**
* @description Sorts an array of objects by given property
@@ -22,6 +26,21 @@ export const sortArrayByProperty = (arr, property) => {
});
};
/**
* @description Replaces placeholder variables in string with given data
* @param {string} str - string to analyse
* @param {object} values - map of variables: values to use
* @returns {string} finished string
*/
export const replacePlaceholder = (str, values) => {
for (let [k, v] of Object.entries(values)) {
str = str.replace(k, v);
console.log(k, v);
}
return str;
};
/**
* @description Used in roll mode, returns selection variables from array
* @param {array} arr - event list
@@ -130,3 +149,59 @@ export const getSelectionByRoll = (arr, now) => {
};
};
/**
* @description Implements update functions for roll mode
* @param {object} currentTimers
* @param {object} currentTimers.selectedEventId - Id of currently selected event
* @param {object} currentTimers.current - Running timer
* @param {object} currentTimers._finishAt - Expected finish time
* @param {object} currentTimers.clock - time now
* @param {object} currentTimers.secondaryTimer - secondary timer
* @param {object} currentTimers._secondaryTarget - finish time of secondary timer
* @returns {object} object with selection variables
*/
export const updateRoll = (currentTimers) => {
const {selectedEventId,current,_finishAt,clock,secondaryTimer,_secondaryTarget} = currentTimers;
// timers
let updatedTimer = current;
let updatedSecondaryTimer = secondaryTimer;
// whether rollLoad should be called
let doRollLoad = false;
// whether runCycle should be called
let isFinished = false;
if (selectedEventId && current >= 0) {
// if we have something selected and a timer, we are running
// this is true because roll never goes into negative times
// update timer
updatedTimer = _finishAt - clock;
if (updatedTimer < 0) {
isFinished = true;
}
console.log(updatedTimer, isFinished, _finishAt)
} else if (secondaryTimer >= 0) {
// if secondaryTimer is running we are in waiting to roll
// update secondary
updatedSecondaryTimer = _secondaryTarget - clock;
}
// if nothing is running, we need to find out if
// a) we just finished an event (finished was set to true)
// b) we need to look for events
// this could be caused by a secondary timer or event finished
const secondaryRunning =
updatedSecondaryTimer <= 0 && updatedSecondaryTimer != null;
if (isFinished || secondaryRunning) {
// look for events
doRollLoad = true;
}
return {updatedTimer, updatedSecondaryTimer, doRollLoad, isFinished};
}
+52
View File
@@ -0,0 +1,52 @@
/** Class contains logic towards outgoing HTTP communications. */
import * as http from 'http';
export class HTTPIntegration {
constructor() {
// nothing to do here
}
/**
* @description Initializes oscClient
* @param {object} httpConfig - Http configurations options
*/
init(httpConfig) {
}
/**
* @description Sends http get request from predefined messages
* @param {string} path - complete http path
*/
async send(path) {
if (path == null) {
console.log('HTTP ERROR: Message undefined');
return;
}
const options = new URL(path);
let str = '';
const req = http.request(options, res => {
console.log(`statusCode: ${res.statusCode}`)
res.on('data', function (chunk) {
str += chunk;
});
res.on('end', function () {
console.log(str);
});
})
req.on('error', error => {
console.error(error)
})
req.end()
}
shutdown() { /* Nothing to shutdown */ }
}
+107
View File
@@ -0,0 +1,107 @@
/** Class contains logic towards outgoing OSC communications. */
import {Client, Message} from 'node-osc';
export class OSCIntegration {
ADDRESS = '/ontime';
constructor() {
// OSC Client
this.oscClient = null;
}
/**
* @description Returns list of implemented messages
* @returns {object} implemented messages
*/
get implemented() {
return {
play: 'play',
pause: 'pause',
stop: 'stop',
previous: 'prev',
next: 'next',
reload: 'reload',
finished: 'finished',
time: 'time',
overtime: 'overtime',
title: 'title',
presenter:'presenter',
}
}
/**
* @description Initializes oscClient
* @param {object} oscConfig - oscClient configuration options
* @param {string} oscConfig.ip - oscClient object
* @param {number} oscConfig.port - OSC Destination Port
*/
init(oscConfig) {
const {ip, port} = oscConfig;
try {
this.oscClient = new Client(ip, port);
console.log(`Initialised OSC Client at ${ip}:${port}`);
} catch (error) {
this.oscClient = null;
console.log(`Failed initialising OSC Client: ${error}`);
}
}
/**
* @description Sends osc from predefined messages
* @param {string} messageType - message to be sent
* @param {string} [payload] - optional payload required in some message types
*/
async send(messageType, payload) {
if (this.oscClient == null) {
console.log('OSC ERROR: Client not initialised');
return;
}
if (messageType == null) {
console.log('OSC ERROR: Message undefined');
return;
}
// only specify special cases
switch (payload) {
case 'overtime':
// Whether timer is negative
this.oscClient.send(`${this.ADDRESS}/overtime`, payload, (err) => {
if (err) console.error(err);
});
break;
case 'title':
if (payload != null && payload !== "") {
// Send Title of current event
this.oscClient.send(`${this.ADDRESS}/title`, payload, (err) => {
if (err) console.error(err);
});
}
break;
case 'presenter':
if (payload != null && payload !== "") {
// Send presenter data on current event
this.oscClient.send(`${this.ADDRESS}/presenter`, payload, (err) => {
if (err) console.error(err);
});
}
break;
default:
// catch all for messages, allows to add new messages
// but should be used with the integrations definition
const message = new Message(`${this.ADDRESS}/${messageType}`)
if (payload != null) message.append(payload)
this.oscClient.send(message, (err) => {
if (err) console.error(err);
});
break;
}
}
shutdown() {
// Shutdown client object
this.oscClient.close();
this.oscClient = null;
}
}