Created
January 5, 2016 21:10
-
-
Save activetheory/08459354b65bca13d061 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 WifiP2P() { | |
Inherit(this, Mobile.BaseModule); | |
var _this = this; | |
var _connected = false; | |
var _message = {fn: 'message'}; | |
var _id = Utils.timestamp(); | |
var _connections = [_id]; | |
var _ping = {}; | |
//*** Constructor | |
(function () { | |
HydraEvents.createLocalEmitter(_this); | |
_this.init(_id); | |
})(); | |
function connected(host) { | |
_connected = true; | |
_this.host = host; | |
_this.sendMessage({newConnection: true}); | |
_this.fire('connected'); | |
} | |
function message(data) { | |
try { | |
var message = JSON.parse(data.data); | |
if (message.id == _id) return; | |
} catch(e) { | |
return; | |
} | |
if (message.newConnection) { | |
if (_this.host) { | |
_connections.push(message.id); | |
_this.sendMessage({startPingTest: true, connections: _connections}, true); | |
} | |
} else if (message.startPingTest) { | |
runPingTest(message); | |
} else if (message.ping) { | |
handleIncomingPing(message); | |
} else { | |
calculateLatency(message); | |
_this.fire('message', message); | |
} | |
} | |
function runPingTest(e) { | |
var conn = e.connections; | |
for (var i = 0; i < conn.length; i++) { | |
var c = conn[i]; | |
if (c == _id) continue; | |
_ping[c] = new Mobile.WifiP2PPing(c, _this); | |
} | |
} | |
function handleIncomingPing(e) { | |
if (e.receiver != _id) return; | |
_ping[e.id].receive(e); | |
} | |
function calculateLatency(e) { | |
var ping = _ping[e.id]; | |
if (!ping) return; | |
var difference = Date.now() - e._time; | |
e.latency = Math.abs(Math.abs(difference) - Math.abs(ping.offset)); | |
} | |
//*** Event handlers | |
//*** Public methods | |
this.incoming = function(data) { | |
switch (data.fn) { | |
case 'connected': connected(data.host); break; | |
case 'message': message(data); break; | |
} | |
} | |
this.sendMessage = function(data, force) { | |
if (!_connected) return; | |
if (!force) data.id = _id; | |
data._time = Date.now(); | |
_message.data = JSON.stringify(data); | |
_this.send(_message); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment