Skip to content

Instantly share code, notes, and snippets.

@activetheory
Created January 5, 2016 21:17
Show Gist options
  • Save activetheory/67c3b7b96146c2acbf30 to your computer and use it in GitHub Desktop.
Save activetheory/67c3b7b96146c2acbf30 to your computer and use it in GitHub Desktop.
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