Skip to content
Snippets Groups Projects
Commit 8cba374a authored by Tomáš Valenta's avatar Tomáš Valenta
Browse files

wip - server-side timer

parent 023cf9af
No related branches found
No related tags found
1 merge request!9Release
Pipeline #14982 passed
import $ from "jquery"
import Timer from "easytimer.js"
import alertify from "alertifyjs";
import "alertifyjs/build/css/alertify.css";
const updateTimeText = (timer) => {
const timeValues = timer.getTimeValues()
const hours = String(timeValues.minutes + timeValues.hours * 60 + timeValues.days * 1440).padStart(2, '0')
const seconds = String(timeValues.seconds).padStart(2, '0')
$('#timer .timer-values').html(`${hours}:${seconds}`)
}
const assignEventListeners = (timer) => {
timer.addEventListener(
'secondsUpdated',
(event) => {
$('#timer .timer-values').html(timer.getTimeValues().toString(['minutes', 'seconds']))
updateTimeText(timer)
}
)
......@@ -17,7 +29,7 @@ const assignEventListeners = (timer) => {
}
)
$('#timer .timer-values').html(timer.getTimeValues().toString(['minutes', 'seconds']))
updateTimeText(timer)
}
$(window).ready(
......@@ -32,7 +44,11 @@ $(window).ready(
}
})
const timerSocket = new WebSocket(
let timerSocket = null
let isInitialConnect = true
const connectToSocket = () => {
timerSocket = new WebSocket(
(
(window.location.protocol === "https:") ?
"wss://" : "ws://"
......@@ -41,7 +57,15 @@ $(window).ready(
+ "/ws/timer/"
)
if (!isInitialConnect) {
alertify.success("Obnovování spojení.")
}
isInitialConnect = false
timerSocket.onmessage = (event) => {
console.log("Received timer message:", event.data)
const data = JSON.parse(event.data)
if ("status" in data) {
......@@ -85,6 +109,14 @@ $(window).ready(
}
}
timerSocket.onclose = (event) => {
alertify.error("Ztráta spojení, pokoušíme se o zpětné připojení.")
setTimeout(connectToSocket, 5000)
}
}
connectToSocket()
assignEventListeners(timer)
// --- END Timer ---
......@@ -120,10 +152,13 @@ $(window).ready(
$("#update-time").on(
"click",
(event) => {
let minutes = Number($("#minutes").val())
let seconds = Number($("#seconds").val())
timerSocket.send(JSON.stringify({
"time": {
"minutes": Number($("#minutes").val()),
"seconds": Number($("#seconds").val())
"minutes": minutes,
"seconds": seconds
}
}))
......
import datetime
import json
from asgiref.sync import async_to_sync
from channels.generic.websocket import WebsocketConsumer
from channels.generic.websocket import AsyncWebsocketConsumer
import time
class TimerConsumer(WebsocketConsumer):
def connect(self):
async_to_sync(self.channel_layer.group_add)("timer", self.channel_name)
class TimerConsumer(AsyncWebsocketConsumer):
timer_is_running = False
self.accept()
async def connect(self) -> None:
await self.channel_layer.group_add("timer", self.channel_name)
await self.accept()
def disconnect(self, close_code):
pass
async def disconnect(self, close_code) -> None:
await self.channel_layer.group_discard("timer", self.channel_name)
def receive(self, text_data):
async def run_timer(self, minutes: int, seconds: int) -> None:
total_seconds = (minutes * 60) + seconds
first_run = True
print("running timer")
for second in range(total_seconds + 1):
if not first_run:
while not self.timer_is_running:
time.sleep(0.05)
# Do on the first run, then every 5 seconds
if first_run or total_seconds % 5 == 0:
new_seconds = total_seconds % 60
new_minutes = round((total_seconds - new_seconds) / 60)
print("sending")
await self.channel_layer.group_send(
"timer",
{
"type": "timer_message",
"text": json.dumps({
"time": {
"minutes": new_minutes,
"seconds": new_seconds
}
})
}
)
if not first_run:
total_seconds -= 1
time.sleep(1)
first_run = False
async def receive(self, text_data: str) -> None:
json_data = json.loads(text_data)
response = None
time_updated = False
if "status" in json_data:
if json_data["status"] == "playing":
response = {"status": "playing"}
self.timer_is_running = True
elif json_data["status"] == "paused":
response = {"status": "paused"}
self.timer_is_running = False
if "time" in json_data:
minutes = json_data["time"]["minutes"]
seconds = json_data["time"]["seconds"]
response = {
"time": {
"minutes": json_data["time"]["minutes"],
"seconds": json_data["time"]["seconds"],
"minutes": minutes,
"seconds": seconds,
}
}
time_updated = True
if response is not None:
async_to_sync(self.channel_layer.group_send)(
"timer", {"type": "timer_message", "text": json.dumps(response)}
)
if time_updated:
await self.run_timer(minutes, seconds)
self.send(text_data=json.dumps({}))
await self.send(text_data=json.dumps({}))
def timer_message(self, event):
self.send(text_data=event["text"])
async def timer_message(self, event: dict) -> None:
await self.send(text_data=event["text"])
......@@ -59,6 +59,8 @@
type="number"
id="minutes"
name="minutes"
min="0"
max="60"
placeholder="Minuty"
autocomplete="off"
>
......@@ -67,6 +69,8 @@
type="number"
id="seconds"
name="seconds"
min="0"
max="60"
placeholder="Sekundy"
autocomplete="off"
>
......
......@@ -33,7 +33,7 @@ module.exports = {
},
output: {
path: path.resolve(__dirname, "shared", "static", "shared"),
filename: "[name]-[fullhash].js",
filename: "[name].js",
},
module: {
rules: [
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment