From 3679d2844af7901cc06f75867eeba1c0cd9ef237 Mon Sep 17 00:00:00 2001 From: Christian Pointner Date: Sat, 18 Jul 2015 03:03:06 +0200 Subject: clock now uses a ntp-style sync format diff --git a/www/js/utils.js b/www/js/utils.js index 74614f0..ea4f42b 100644 --- a/www/js/utils.js +++ b/www/js/utils.js @@ -124,12 +124,12 @@ function Clock(draw_callback) { this.draw_callback = draw_callback; this.daynames = new Array('So', 'Mo', 'Di', 'Mi', 'Do', 'Fr', 'Sa'); - this.last_update = { timestamp: 0, tz_offset: 3600, week: 3 }; + this.last_message = { t1: 0, t2: 0, t3: 0, t4: 0, tz_offset: 3600, week: 3 }; this.clock_offset = 0; + this.clock_rtt = 0; this.redraw = function() { -// console.log("redraw called"); - var rdtime_ms = (+new Date()) + (this.last_update.tz_offset * 1000) + this.clock_offset; + var rdtime_ms = (+new Date()) + (this.last_message.tz_offset * 1000) + this.clock_offset; var rdtime = new Date(rdtime_ms); var date_str = this.daynames[rdtime.getUTCDay()] + ', '; @@ -139,24 +139,40 @@ function Clock(draw_callback) { time_str += (rdtime.getUTCMinutes() > 9 ? ':' : ':0') + rdtime.getUTCMinutes(); time_str += (rdtime.getUTCSeconds() > 9 ? ':' : ':0') + rdtime.getUTCSeconds(); - this.draw_callback(date_str, time_str, this.last_update.week); + this.draw_callback(date_str, time_str, this.last_message.week); } - this.update = function(event) { - var update = JSON.parse(event.data); - this.last_update = update; - this.clock_offset = (update.timestamp*1000) - (+new Date()) ; -// console.log("got new timeupdate from rhrdtime: new offset = " + this.clock_offset + " ms"); + this.ntp_update = function(event) { + var t4 = (+new Date()); + + var msg = JSON.parse(event.data); + msg.t4 = t4; + this.last_message = msg; + this.clock_offset = ((msg.t2 - msg.t1) + (msg.t3 - msg.t4)) / 2; + this.clock_rtt = (msg.t4 - msg.t1) - (msg.t3 - msg.t2); + console.log("got new ntp message from rhrdtime (rtt=" + this.clock_rtt + " ms): new offset = " + this.clock_offset + " ms"); + } + + this.ntp_request = function() { + this.sock.send(JSON.stringify({ t1: (+new Date()), t2: 0, t3: 0, t4: 0, tz_offset: 0, week: 0 })); + } + + this.sock_onopen = function() { + this.ntp_request(); + this.interval_redraw = setInterval(this.ntp_request.bind(this), 5000); } this.start = function() { - this.sock = new WebSocket("wss://import.helsinki.at/time"); - this.sock.onmessage = this.update.bind(this); - this.interval = setInterval(this.redraw.bind(this), 500); + this.sock = new WebSocket("wss://import.helsinki.at/ntp"); + this.sock.onmessage = this.ntp_update.bind(this); + this.sock.onopen = this.sock_onopen.bind(this); + this.interval_redraw = setInterval(this.redraw.bind(this), 200); } this.stop = function() { - clearInterval(this.interval); - delete this.interval; + clearInterval(this.interval_redraw); + delete this.interval_redraw; + clearInterval(this.interval_request); + delete this.interval_request; this.sock.close(); } } -- cgit v0.10.2