inti relative mode

This commit is contained in:
arc-alex
2025-02-25 22:25:38 +01:00
parent 0a6542df76
commit 140a3310cb
21 changed files with 248 additions and 21 deletions
+1 -1
View File
@@ -19,7 +19,7 @@ import * as projectService from '../../services/project-service/ProjectService.j
export async function patchPartialProjectFile(req: Request, res: Response<DatabaseModel | ErrorResponse>) {
try {
const { rundown, project, settings, viewSettings, urlPresets, customFields, automation } = req.body;
const patchDb: DatabaseModel = {
const patchDb: Partial<DatabaseModel> = {
rundown,
project,
settings,
@@ -1,4 +1,4 @@
import { MessageState, OntimeEvent, SimpleDirection, SimplePlayback } from 'ontime-types';
import { MessageState, OffsetMode, OntimeEvent, SimpleDirection, SimplePlayback } from 'ontime-types';
import { MILLIS_PER_HOUR, MILLIS_PER_SECOND } from 'ontime-utils';
import { DeepPartial } from 'ts-essentials';
@@ -17,6 +17,7 @@ import { throttle } from '../utils/throttle.js';
import { willCauseRegeneration } from '../services/rundown-service/rundownCacheUtils.js';
import { handleLegacyMessageConversion } from './integration.legacy.js';
import { coerceEnum } from '../utils/coerceType.js';
const throttledUpdateEvent = throttle(updateEvent, 20);
let lastRequest: Date | null = null;
@@ -286,6 +287,11 @@ const actionHandlers: Record<string, ActionHandler> = {
throw new Error('No matching method provided');
},
offsetmode: (payload) => {
const mode = coerceEnum<OffsetMode>(payload, OffsetMode);
runtimeService.setOffsetMode(mode);
return { payload: 'success' };
},
};
/**
+3
View File
@@ -170,6 +170,8 @@ export const startServer = async (
socket.init(expressServer, showWelcome, prefix);
const offsetMode = getDataProvider().getOffsetMode();
/**
* Module initialises the services and provides initial payload for the store
*/
@@ -210,6 +212,7 @@ export const startServer = async (
// TODO: pass event store to rundownservice
runtimeService.init(maybeRestorePoint);
runtimeService.setOffsetMode(offsetMode);
const nif = getNetworkInterfaces();
consoleSuccess(`Local: http://localhost:${resultPort}${prefix}/editor`);
@@ -7,6 +7,7 @@ import {
CustomFields,
URLPreset,
AutomationSettings,
OffsetMode,
} from 'ontime-types';
import type { Low } from 'lowdb';
@@ -55,6 +56,8 @@ export function getDataProvider() {
setAutomation,
getRundown,
mergeIntoData,
getOffsetMode,
setOffsetMode,
};
}
@@ -132,6 +135,17 @@ function getRundown(): Readonly<OntimeRundown> {
return db.data.rundown;
}
function getOffsetMode(): Readonly<OffsetMode> {
return db.data.offsetMode;
}
async function setOffsetMode(mode): ReadonlyPromise<OffsetMode> {
db.data.offsetMode = mode;
//TODO: should this maybe not be persisted every time
await persist();
return db.data.offsetMode;
}
async function mergeIntoData(newData: Partial<DatabaseModel>): ReadonlyPromise<DatabaseModel> {
const mergedData = safeMerge(db.data, newData);
db.data.project = mergedData.project;
@@ -1,4 +1,4 @@
import { DatabaseModel, OntimeRundown, Settings, URLPreset, ViewSettings } from 'ontime-types';
import { DatabaseModel, OffsetMode, OntimeRundown, Settings, URLPreset, ViewSettings } from 'ontime-types';
import { safeMerge } from '../DataProvider.utils.js';
describe('safeMerge', () => {
@@ -42,6 +42,7 @@ describe('safeMerge', () => {
triggers: [],
automations: {},
},
offsetMode: OffsetMode.Absolute,
} as DatabaseModel;
it('returns existing data if new data is not provided', () => {
+2 -1
View File
@@ -1,4 +1,4 @@
import { DatabaseModel } from 'ontime-types';
import { DatabaseModel, OffsetMode } from 'ontime-types';
import { ONTIME_VERSION } from '../ONTIME_VERSION.js';
export const dbModel: DatabaseModel = {
@@ -38,4 +38,5 @@ export const dbModel: DatabaseModel = {
triggers: [],
automations: {},
},
offsetMode: OffsetMode.Absolute,
};
+2 -1
View File
@@ -1,4 +1,4 @@
import { DatabaseModel, EndAction, SupportedEvent, TimeStrategy, TimerType } from 'ontime-types';
import { DatabaseModel, EndAction, OffsetMode, SupportedEvent, TimeStrategy, TimerType } from 'ontime-types';
export const demoDb: DatabaseModel = {
rundown: [
@@ -457,4 +457,5 @@ export const demoDb: DatabaseModel = {
triggers: [],
automations: {},
},
offsetMode: OffsetMode.Absolute,
};
@@ -4,6 +4,7 @@ import { EndAction, Playback, TimeStrategy, TimerPhase, TimerType } from 'ontime
import {
getCurrent,
getExpectedFinish,
getRelativeOffset,
getRuntimeOffset,
getTimerPhase,
normaliseEndTime,
@@ -1046,6 +1047,84 @@ describe('getRuntimeOffset()', () => {
});
});
describe('getRelativeOffset()', () => {
it('relative offset is 0 when starting at the planed time', () => {
const state = {
eventNow: {
id: '1',
timeStart: 150,
},
timer: {
startedAt: 150,
addedTime: 0,
current: 0,
},
_timer: {
pausedAt: null,
},
runtime: {
actualStart: 150,
plannedStart: 150,
},
} as RuntimeState;
state.runtime.offset = getRuntimeOffset(state);
expect(state.runtime.offset).toBe(0);
const relativeOffsetoffset = getRelativeOffset(state);
expect(relativeOffsetoffset).toBe(0);
});
it('relative offset is 0 when starting after the planed time', () => {
const state = {
eventNow: {
id: '1',
timeStart: 100,
},
timer: {
startedAt: 150,
addedTime: 0,
current: 0,
},
_timer: {
pausedAt: null,
},
runtime: {
actualStart: 150,
plannedStart: 100,
},
} as RuntimeState;
state.runtime.offset = getRuntimeOffset(state);
expect(state.runtime.offset).toBe(-50);
const relativeOffsetoffset = getRelativeOffset(state);
expect(relativeOffsetoffset).toBe(0);
});
it('relative offset is 0 when starting before the planed time', () => {
const state = {
eventNow: {
id: '1',
timeStart: 150,
},
timer: {
startedAt: 100,
addedTime: 0,
current: 0,
},
_timer: {
pausedAt: null,
},
runtime: {
actualStart: 100,
plannedStart: 150,
},
} as RuntimeState;
state.runtime.offset = getRuntimeOffset(state);
expect(state.runtime.offset).toBe(50);
const relativeOffsetoffset = getRelativeOffset(state);
expect(relativeOffsetoffset).toBe(0);
});
});
describe('getTimerPhase()', () => {
it('should be None if the timer is not running', () => {
const state = {
@@ -4,6 +4,7 @@ import {
isPlayableEvent,
LogOrigin,
MaybeNumber,
OffsetMode,
OntimeEvent,
Playback,
TimerLifeCycle,
@@ -37,6 +38,7 @@ import {
import { getForceUpdate, getShouldClockUpdate, getShouldTimerUpdate } from './rundownService.utils.js';
import { skippedOutOfEvent } from '../timerUtils.js';
import { triggerAutomations } from '../../api-data/automation/automation.service.js';
import { getDataProvider } from '../../classes/data-provider/DataProvider.js';
type RuntimeStateEventKeys = keyof Pick<RuntimeState, 'eventNext' | 'eventNow' | 'publicEventNow' | 'publicEventNext'>;
@@ -68,6 +70,14 @@ class RuntimeService {
RuntimeService.previousState = {} as RuntimeState;
}
@broadcastResult
setOffsetMode(mode: OffsetMode) {
runtimeState.setOffsetMode(mode);
process.nextTick(() => {
getDataProvider().setOffsetMode(mode);
});
}
/**
* Checks result of an update and notifies integrations as needed
* This is the only exception of a private method that has broadcast result
+10
View File
@@ -156,6 +156,16 @@ export function getRuntimeOffset(state: RuntimeState): number {
return startOffset - addedTime - pausedTime + overtime;
}
/**
* Calculates relative offset
* should always be calculated after the absolute offset
*/
export function getRelativeOffset(state: RuntimeState): number {
const { actualStart, plannedStart } = state.runtime;
const relativeStartOffset = actualStart - plannedStart;
return state.runtime.offset + relativeStartOffset;
}
/**
* Calculates the expected end of the rundown
*/
@@ -1,4 +1,4 @@
import { TimerPhase, Playback } from 'ontime-types';
import { TimerPhase, Playback, OffsetMode } from 'ontime-types';
import { deepmerge } from 'ontime-utils';
import type { RuntimeState } from '../runtimeState.js';
@@ -16,10 +16,12 @@ const baseState: RuntimeState = {
selectedEventIndex: null,
numEvents: 0,
offset: 0,
relativeOffset: 0,
plannedStart: 0,
plannedEnd: 0,
actualStart: null,
expectedEnd: null,
offsetMode: OffsetMode.Absolute,
},
timer: {
addedTime: 0,
@@ -4,7 +4,7 @@ import { deepmerge } from 'ontime-utils';
import {
type RuntimeState,
addTime,
clear,
hardClear,
getState,
load,
loadBlock,
@@ -71,7 +71,7 @@ beforeAll(() => {
describe('mutation on runtimeState', () => {
beforeEach(() => {
clear();
hardClear();
vi.mock('../../services/rundown-service/RundownService.js', async (importOriginal) => {
const actual = (await importOriginal()) as object;
@@ -246,7 +246,7 @@ describe('roll mode', () => {
beforeEach(() => {
vi.useFakeTimers();
vi.setSystemTime('jan 1 00:00');
clear();
hardClear();
});
afterEach(() => {
vi.useRealTimers();
+42 -10
View File
@@ -3,6 +3,7 @@ import {
isPlayableEvent,
MaybeNumber,
MaybeString,
OffsetMode,
OntimeEvent,
OntimeRundown,
PlayableEvent,
@@ -27,6 +28,7 @@ import {
getCurrent,
getExpectedEnd,
getExpectedFinish,
getRelativeOffset,
getRuntimeOffset,
getTimerPhase,
} from '../services/timerUtils.js';
@@ -82,7 +84,32 @@ export function getState(): Readonly<RuntimeState> {
};
}
export function clear() {
//TODO: find other thinbgs that dose not need clearing
export function softClear() {
runtimeState.eventNow = null;
runtimeState.publicEventNow = null;
runtimeState.eventNext = null;
runtimeState.publicEventNext = null;
// runtimeState.currentBlock.block = null;
// runtimeState.currentBlock.startedAt = null;
runtimeState.runtime.offset = 0;
runtimeState.runtime.relativeOffset = 0;
runtimeState.runtime.expectedEnd = null;
runtimeState.runtime.selectedEventIndex = null;
runtimeState.timer.playback = Playback.Stop;
runtimeState.clock = clock.timeNow();
runtimeState.timer = { ...runtimeStorePlaceholder.timer };
// when clearing, we maintain the total delay from the rundown
runtimeState._timer.forceFinish = null;
runtimeState._timer.pausedAt = null;
runtimeState._timer.secondaryTarget = null;
}
export function hardClear() {
runtimeState.eventNow = null;
runtimeState.publicEventNow = null;
runtimeState.eventNext = null;
@@ -93,6 +120,7 @@ export function clear() {
runtimeState.publicEventNext = null;
runtimeState.runtime.offset = 0;
runtimeState.runtime.relativeOffset = 0;
runtimeState.runtime.actualStart = null;
runtimeState.runtime.expectedEnd = null;
runtimeState.runtime.selectedEventIndex = null;
@@ -155,9 +183,9 @@ export function load(
initialData?: Partial<TimerState & RestorePoint>,
): boolean {
// we need to persist the current block state across loads
const prevCurrentBlock = { ...runtimeState.currentBlock };
clear();
runtimeState.currentBlock = prevCurrentBlock;
// const prevCurrentBlock = { ...runtimeState.currentBlock };
softClear();
// runtimeState.currentBlock = prevCurrentBlock;
// filter rundown
const timedEvents = filterTimedEvents(rundown);
@@ -185,6 +213,7 @@ export function load(
if (firstStart === null || typeof firstStart === 'number') {
runtimeState.runtime.actualStart = firstStart;
runtimeState.runtime.offset = getRuntimeOffset(runtimeState);
runtimeState.runtime.relativeOffset = getRelativeOffset(runtimeState);
runtimeState.runtime.expectedEnd = getExpectedEnd(runtimeState);
}
if (typeof initialData.blockStartAt === 'number') {
@@ -390,6 +419,7 @@ export function start(state: RuntimeState = runtimeState): boolean {
// update offset
state.runtime.offset = getRuntimeOffset(state);
state.runtime.relativeOffset = getRelativeOffset(state);
state.runtime.expectedEnd = state.runtime.plannedEnd - state.runtime.offset;
return true;
}
@@ -409,9 +439,7 @@ export function stop(state: RuntimeState = runtimeState): boolean {
if (state.timer.playback === Playback.Stop) {
return false;
}
clear();
runtimeState.runtime.actualStart = null;
runtimeState.runtime.expectedEnd = null;
hardClear();
return true;
}
@@ -453,6 +481,7 @@ export function addTime(amount: number) {
// update runtime delays: over - under
runtimeState.runtime.offset = getRuntimeOffset(runtimeState);
runtimeState.runtime.relativeOffset = getRelativeOffset(runtimeState);
runtimeState.runtime.expectedEnd = getExpectedEnd(runtimeState);
return true;
@@ -498,6 +527,7 @@ export function update(): UpdateResult {
// update runtime, needs up-to-date timer state
runtimeState.runtime.offset = getRuntimeOffset(runtimeState);
runtimeState.runtime.relativeOffset = getRelativeOffset(runtimeState);
runtimeState.runtime.expectedEnd = getExpectedEnd(runtimeState);
const finishedNow =
@@ -604,9 +634,7 @@ export function roll(rundown: OntimeRundown, offset = 0): { eventId: MaybeString
}
// we need to persist the current block state across loads
const prevCurrentBlock = { ...runtimeState.currentBlock };
clear();
runtimeState.currentBlock = prevCurrentBlock;
softClear();
//account for offset but we only keep it if passed to us
runtimeState.runtime.offset = offset;
@@ -696,3 +724,7 @@ export function loadBlock(rundown: OntimeRundown, state = runtimeState) {
// update the block anyway
state.currentBlock.block = newCurrentBlock === null ? null : { ...newCurrentBlock };
}
export function setOffsetMode(mode: OffsetMode) {
runtimeState.runtime.offsetMode = mode;
}
+9 -1
View File
@@ -27,7 +27,14 @@ import { logger } from '../classes/Logger.js';
import { event as eventDef } from '../models/eventsDefinition.js';
import { makeString } from './parserUtils.js';
import { parseProject, parseRundown, parseSettings, parseUrlPresets, parseViewSettings } from './parserFunctions.js';
import {
parseOffsetMode,
parseProject,
parseRundown,
parseSettings,
parseUrlPresets,
parseViewSettings,
} from './parserFunctions.js';
import { parseExcelDate } from './time.js';
export type ErrorEmitter = (message: string) => void;
@@ -336,6 +343,7 @@ export function parseDatabaseModel(jsonData: Partial<DatabaseModel>): { data: Da
urlPresets: parseUrlPresets(jsonData, makeEmitError('URL Presets')),
customFields,
automation: parseAutomationSettings(jsonData),
offsetMode: parseOffsetMode(jsonData, makeEmitError('OffsetMode')),
};
return { data, errors };
+21
View File
@@ -2,6 +2,7 @@ import {
CustomField,
CustomFields,
DatabaseModel,
OffsetMode,
OntimeBlock,
OntimeDelay,
OntimeEvent,
@@ -20,6 +21,7 @@ import { customFieldLabelToKey, generateId, isAlphanumericWithSpace } from 'onti
import { dbModel } from '../models/dataModel.js';
import { block as blockDef, delay as delayDef } from '../models/eventsDefinition.js';
import { createEvent, type ErrorEmitter } from './parser.js';
import { coerceEnum } from './coerceType.js';
/**
* Parse rundown array of an entry
@@ -117,6 +119,25 @@ export function parseProject(data: Partial<DatabaseModel>, emitError?: ErrorEmit
};
}
/**
* Parse offsetmode
*/
export function parseOffsetMode(data: Partial<DatabaseModel>, emitError?: ErrorEmitter): OffsetMode {
if (!data.offsetMode) {
emitError?.('No offsetmode found to import');
return dbModel.offsetMode;
}
console.log('Found offsetmode, importing...');
try {
return coerceEnum<OffsetMode>(data.offsetMode, OffsetMode);
} catch (error) {
emitError?.('Invalid offsetmode found');
return dbModel.offsetMode;
}
}
/**
* Parse settings portion of an entry
*/