Created
January 5, 2016 21:17
-
-
Save activetheory/67c3b7b96146c2acbf30 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Mobile.Class(function WifiP2PPing(_id, _parent) { | |
var _this = this; | |
var _results = []; | |
var _messages = {}; | |
//*** Constructor | |
(function () { | |
setTimeout(send, 500); | |
})(); | |
function send() { | |
var message = {}; | |
message.ping = true; | |
message._id = Utils.timestamp(); | |
message.outTime = Date.now(); | |
message.receiver = _id; | |
_messages[message._id] = message; | |
_parent.sendMessage(message); | |
} | |
function calculate() { | |
_results.sort(function(a, b) { | |
return a - b; | |
}); | |
_this.offset = _results[5]; | |
} | |
//*** Event handlers | |
//*** Public methods | |
this.receive = function(incoming) { | |
var outgoing = _messages[incoming._id]; | |
if (!outgoing) { | |
incoming.inTime = Date.now(); | |
incoming.receiver = _id; | |
_parent.sendMessage(incoming); | |
} else { | |
var currentTime = Date.now(); | |
var latency = Math.round((currentTime - outgoing.outTime) * 0.5); | |
var pairTime = incoming.inTime; | |
currentTime -= latency; | |
var difference = currentTime - pairTime; | |
console.log(latency, difference); | |
_results.push(difference); | |
_this.offset = difference; | |
if (_results.length < 11) setTimeout(send, 500); | |
else calculate(); | |
} | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment