From 2ae991a2c323801b4077537b73f2696eda34d136 Mon Sep 17 00:00:00 2001 From: cv <34649812+cpvalente@users.noreply.github.com> Date: Thu, 8 Apr 2021 13:41:51 +0200 Subject: [PATCH] timer control --- .../src/features/control/PlaybackControl.jsx | 68 ++++++--- client/src/features/editors/Editor.jsx | 37 +---- server/app.js | 19 ++- server/config.json | 3 + server/controllers/playbackController.js | 47 ++++++- server/routes/playbackRouter.js | 28 ++-- server/timer.js | 129 ++++++++++++++---- 7 files changed, 226 insertions(+), 105 deletions(-) diff --git a/client/src/features/control/PlaybackControl.jsx b/client/src/features/control/PlaybackControl.jsx index aa6af46f3..603f660df 100644 --- a/client/src/features/control/PlaybackControl.jsx +++ b/client/src/features/control/PlaybackControl.jsx @@ -10,7 +10,8 @@ import { } from 'react-icons/fi'; import { format } from 'date-fns'; import { timeFormatSeconds } from '../../common/dateConfig'; -import { useState } from 'react'; +import { useEffect, useState } from 'react'; +import { io } from 'socket.io-client'; // BUTTON DEFINITION const defProps = { @@ -23,39 +24,59 @@ const size = { }; export default function PlaybackControl(props) { - const { timer, roll } = props; - const { playback } = useState(props.playback); + const [playback, setPlayback] = useState(null); + const [timer, setTimer] = useState({ + currentSeconds: null, + startedAt: null, + expectedFinish: null, + }); + const updateTimer = (vals) => { + setTimer({ ...timer, ...vals }); + }; + // TODO: Move to config file + const serverURL = 'http://localhost:4001/'; + const playbackURL = serverURL + 'playback/'; + + // WEBSOCKETZ + useEffect(() => { + // TODO: add namespace? + const socket = io(serverURL, { transport: ['websocket'] }); + console.log('websocket started'); + + // Handle timer + socket.on('timer', (data) => { + updateTimer(data); + }); + + return () => socket.disconnect(); + }, []); const playbackControl = async (action, payload) => { switch (action) { - case 'play': { - const pb = await fetch('http://localhost:4001/play').then((res) => - console.log(res) + case 'start': { + await fetch(playbackURL + 'start').then( + (res) => res.ok && setPlayback('start') ); break; } case 'pause': { - const pb = await fetch('http://localhost:4001/pause').then((res) => - console.log(res) + await fetch(playbackURL + 'pause').then( + (res) => res.ok && setPlayback('pause') ); break; } case 'roll': { - const pb = await fetch('http://localhost:4001/roll').then((res) => - console.log(res) + await fetch(playbackURL + 'roll').then( + (res) => res.ok && setPlayback('roll') ); break; } case 'previous': { - const pb = await fetch('http://localhost:4001/previous').then((res) => - console.log(res) - ); + await fetch(playbackURL + 'previous').then((res) => console.log(res)); break; } case 'next': { - const pb = await fetch('http://localhost:4001/next').then((res) => - console.log(res) - ); + await fetch(playbackURL + 'next').then((res) => console.log(res)); break; } default: @@ -63,18 +84,18 @@ export default function PlaybackControl(props) { } }; - const started = timer.started - ? format(timer.started, timeFormatSeconds) + const started = timer.startedAt + ? format(timer.startedAt, timeFormatSeconds) : '...'; - const finish = timer.started - ? format(timer.finish, timeFormatSeconds) + const finish = timer.expectedFinish + ? format(timer.expectedFinish, timeFormatSeconds) : '...'; return (
- +
Started at @@ -91,13 +112,15 @@ export default function PlaybackControl(props) { {...size} icon={} colorScheme='green' - onClick={() => playbackControl('play')} + onClick={() => playbackControl('start')} + variant={playback === 'start' ? 'solid' : 'outline'} /> } colorScheme='orange' onClick={() => playbackControl('pause')} + variant={playback === 'pause' ? 'solid' : 'outline'} /> } colorScheme='blue' onClick={() => playbackControl('roll')} + variant={playback === 'roll' ? 'solid' : 'outline'} />
diff --git a/client/src/features/editors/Editor.jsx b/client/src/features/editors/Editor.jsx index 8d9432fd9..63416cfc7 100644 --- a/client/src/features/editors/Editor.jsx +++ b/client/src/features/editors/Editor.jsx @@ -12,7 +12,6 @@ import MessageForm from '../form/MessageForm'; import PreviewContainer from '../viewers/PreviewContainer'; import styles from './Editor.module.css'; import EventList from './list/EventList'; -import { io } from 'socket.io-client'; export default function Editor() { const [formMode, setFormMode] = useState(null); @@ -30,38 +29,7 @@ export default function Editor() { const updatePlayback = (vals) => { setPlayback({ ...playback, ...vals }); }; - const [timer, setTimer] = useState({ - current: null, - duration: null, - started: null, - finished: null, - }); - const updateTimer = (vals) => { - setTimer({ ...timer, ...vals }); - }; - // WEBSOCKETZ - useEffect(() => { - // TODO: add namespace? - const socket = io('http://localhost:4001', { transport: ['websocket'] }); - console.log('websocket started'); - - // Handle timer - socket.on('timer', (data) => { - console.log('got time', data); - updateTimer(data); - }); - - // Handle events - socket.on('eventdata', (data) => { - console.log('got eventdata', data); - setWebEvents(data); - }); - - return () => socket.disconnect(); - }, []); - - console.log('playback here', playback); console.log('events here', webEvents); return ( @@ -123,10 +91,7 @@ export default function Editor() {
- +
diff --git a/server/app.js b/server/app.js index fe56481e7..bac88584e 100644 --- a/server/app.js +++ b/server/app.js @@ -5,18 +5,28 @@ const config = require('./config.json'); const express = require('express'); const http = require('http'); const socketIo = require('socket.io'); +const cors = require('cors'); // Import Routes const eventsRouter = require('./routes/eventsRouter.js'); const playbackRouter = require('./routes/playbackRouter.js'); -// TODO: Move to config file // Setup default port -const port = process.env.PORT || 4001; +const port = process.env.PORT || config.server.port; + +// Global Objects +const Timer = require('./timer.js'); +// TODO: this should be replaced by some sort of calculation +let durationForNow = 5400; +global.timer = new Timer(); +timer.setupWithSeconds(durationForNow, true); // Create express APP const app = express(); +// setup cors for all routes +app.use(cors()); + // Implement middleware // --- @@ -41,11 +51,6 @@ const io = socketIo(server, { }, }); -const Timer = require('./timer.js'); -// TODO: this should be replaced by some sort of calculation -let durationForNow = 5400; -let timer = new Timer(durationForNow); - // interval function let interval; diff --git a/server/config.json b/server/config.json index b2d333035..93f49f264 100644 --- a/server/config.json +++ b/server/config.json @@ -1,5 +1,8 @@ { "timer": { "refresh": 1000 + }, + "server": { + "port": 4001 } } \ No newline at end of file diff --git a/server/controllers/playbackController.js b/server/controllers/playbackController.js index 612e4c898..5a3943cbc 100644 --- a/server/controllers/playbackController.js +++ b/server/controllers/playbackController.js @@ -1,16 +1,59 @@ // import json with initial data const playbackState = require('../data/playbackData.json'); -// Create controller for GET request to '/pb' +// Create controller for GET request to '/playback' // Returns ACK message exports.pbGet = async (req, res) => { // ?? Do i need to wrap this in an object? res.send({ response: 'Playback Controller API' }); }; -// Create controller for GET request to '/pb/all' +// Create controller for GET request to '/playback/all' // Returns playback state object exports.pbGetAll = async (req, res) => { res.json(playbackState); }; +// Create controller for GET request to '/playback/start' +// Starts timer object +exports.pbStart = async (req, res) => { + console.log('start request'); + global.timer.start(); + res.sendStatus(200); +}; + +// Create controller for GET request to '/playback/pause' +// Pauses timer object +exports.pbPause = async (req, res) => { + console.log('pause request'); + global.timer.pause(); + res.sendStatus(200); +}; + +// Create controller for GET request to '/playback/stop' +// Stops timer object +exports.pbStop = async (req, res) => { + global.timer.stop(); + res.sendStatus(200); +}; + +// Create controller for GET request to '/playback/roll' +// Sets timer object to roll mode +exports.pbRoll = async (req, res) => { + global.timer.roll(); + res.sendStatus(501); +}; + +// Create controller for GET request to '/playback/previous' +// Sets timer object to roll mode +exports.pbPrevious = async (req, res) => { + console.log('previous: not implemented'); + res.sendStatus(501); +}; + +// Create controller for GET request to '/playback/next' +// Sets timer object to roll mode +exports.pbNext = async (req, res) => { + console.log('next: not implemented'); + res.sendStatus(501); +}; diff --git a/server/routes/playbackRouter.js b/server/routes/playbackRouter.js index dea923a09..a066fd770 100644 --- a/server/routes/playbackRouter.js +++ b/server/routes/playbackRouter.js @@ -1,19 +1,31 @@ const express = require('express'); -const cors = require('cors'); const router = express.Router(); -// Cross origin stuff -const corsOptions = { - origin: 'http://localhost', -}; - // import event controller const playbackController = require('../controllers/playbackController'); // create route between controller and '/playback' endpoint -router.get('/', cors(corsOptions), playbackController.pbGet); +router.get('/', playbackController.pbGet); // create route between controller and '/playback/all' endpoint -router.get('/all', cors(corsOptions), playbackController.pbGetAll); +router.get('/all', playbackController.pbGetAll); + +// create route between controller and '/playback/start' endpoint +router.get('/start', playbackController.pbStart); + +// create route between controller and '/playback/pause' endpoint +router.get('/pause', playbackController.pbPause); + +// create route between controller and '/playback/stop' endpoint +router.get('/stop', playbackController.pbStop); + +// create route between controller and '/playback/roll' endpoint +router.get('/roll', playbackController.pbRoll); + +// create route between controller and '/playback/previous' endpoint +router.get('/previous',playbackController.pbPrevious); + +// create route between controller and '/playback/next' endpoint +router.get('/next', playbackController.pbNext); module.exports = router; diff --git a/server/timer.js b/server/timer.js index fc8a3cd57..288abab86 100644 --- a/server/timer.js +++ b/server/timer.js @@ -1,56 +1,125 @@ class Timer { - constructor(durationInSeconds) { + #current = null; + #finishAt = null; + #startedAt = null; + #pausedAt = null; + #pausedInterval = null; + #pausedTotal = null; + state = 'pause'; + + constructor() {} + + // call setup separately + setupWithSeconds(seconds, autoStart = false) { + // aux const now = new Date().getTime(); - this.duration = durationInSeconds; - this.current = durationInSeconds; - this.finish = new Date().getTime() + durationInSeconds * 1000; - this.started = now; + + // populate targets + 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() { - // doesnt include start time yet + // get current time const now = new Date().getTime(); - this.current = (this.finish - now) * 0.001; + + // check playstate + switch (this.state) { + case 'start': + // update current timer + this.#current = this.#finishAt + this.#pausedTotal - now; + break; + case 'pause': + // update paused time + this.#pausedInterval = now - this.#pausedAt; + break; + default: + console.error('Timer: no playstate on update call', this.state); + break; + } + } + + // helpers + static toSeconds(millis) { + return Math.floor(Math.max(millis * 0.001), 0); + } + + #getExpectedFinish() { + return ( + this.#finishAt + + (this.#pausedInterval + this.#pausedTotal) + ); } // getObject getObject() { this.update(); return { - duration: this.duration, - current: this.current, - finish: this.finish, - started: this.started, + currentSeconds: Timer.toSeconds(this.#current), + expectedFinish: this.#getExpectedFinish(), + startedAt: this.#startedAt, }; } - // duration - getDuration(durationInSeconds) { - return this.duration; - } - setDuration() { - try { - this.duration = durationInSeconds; - return true; - } catch (e) { - console.error(e); - return false; - } - } - // current time in seconds getCurrentInSeconds() { // update timeStamp this.update(); - return this.current; + return Timer.toSeconds(this.#current); } // playback - start() {} - pause() {} - // playback - stop() {} + start() { + // do we need to change + if (this.state === 'start') return; + + // update start time if needed + if (!this.#startedAt) { + this.#startedAt = new Date().getTime(); + } + + // check if there is paused time + if (this.#pausedInterval) { + this.#pausedTotal += this.#pausedInterval; + this.#pausedInterval = null; + } + + // change state + this.state = 'start'; + console.log('started'); + } + pause() { + // do we need to change + if (this.state === 'pause') return; + + // update pause time + this.#pausedAt = new Date().getTime(); + + // change state + this.state = 'pause'; + + console.log('paused'); + } + stop() { + console.log('stop: not yet implemented'); + return false; + } + roll() { + console.log('roll: not yet implemented'); + return false; + } } module.exports = Timer;