Skip to content

Commit

Permalink
feat: add logger class (#434)
Browse files Browse the repository at this point in the history
* add logger class and replace it

* add enable/disable on logger
  • Loading branch information
kannan-xiao4 authored Mar 3, 2021
1 parent 7be7ea7 commit fc99f34
Show file tree
Hide file tree
Showing 7 changed files with 101 additions and 66 deletions.
1 change: 0 additions & 1 deletion WebApp/public/bidirectional/js/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@ async function setupConfig() {
const res = await getServerConfig();
useWebSocket = res.useWebSocket;
showWarningIfNeeded(res.startupMode);
showPlayButton();
}

function showWarningIfNeeded(startupMode) {
Expand Down
23 changes: 12 additions & 11 deletions WebApp/public/bidirectional/js/sendvideo.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import Signaling, { WebSocketSignaling } from "../../js/signaling.js";
import * as Config from "../../js/config.js";
import * as Logger from "../../js/logger.js";

export class SendVideo {
constructor() {
Expand All @@ -18,7 +19,7 @@ export class SendVideo {
localVideo.srcObject = this.localStream;
await localVideo.play();
} catch (err) {
console.error('mediaDevice.getUserMedia() error:', err);
Logger.error('mediaDevice.getUserMedia() error:', err);
}
}

Expand Down Expand Up @@ -94,7 +95,7 @@ export class SendVideo {
this.isOffer = isOffer;
// close current RTCPeerConnection
if (this.pc) {
console.log('Close current PeerConnection');
Logger.log('Close current PeerConnection');
this.pc.close();
this.pc = null;
}
Expand All @@ -103,19 +104,19 @@ export class SendVideo {
this.pc = new RTCPeerConnection(this.config);

this.pc.onsignalingstatechange = e => {
console.log('signalingState changed:', e);
Logger.log('signalingState changed:', e);
};

this.pc.oniceconnectionstatechange = e => {
console.log('iceConnectionState changed:', e);
console.log('pc.iceConnectionState:' + _this.pc.iceConnectionState);
Logger.log('iceConnectionState changed:', e);
Logger.log('pc.iceConnectionState:' + _this.pc.iceConnectionState);
if (_this.pc.iceConnectionState === 'disconnected') {
_this.hangUp();
}
};

this.pc.onicegatheringstatechange = e => {
console.log('iceGatheringState changed:', e);
Logger.log('iceGatheringState changed:', e);
};

this.pc.ontrack = async (e) => {
Expand All @@ -138,15 +139,15 @@ export class SendVideo {
async sendOffer() {
const _this = this;
let offer = await _this.pc.createOffer();
console.log('createOffer() succsess in promise');
Logger.log('createOffer() succsess in promise');

if (_this.pc.signalingState != 'stable') {
console.error("peerConnection's signaling state is not stable. " + pc.SignalingState);
Logger.error("peerConnection's signaling state is not stable. " + pc.SignalingState);
return;
}

await _this.pc.setLocalDescription(offer);
console.log('setLocalDescription() succsess in promise');
Logger.log('setLocalDescription() succsess in promise');
_this.signaling.sendOffer(_this.connectionId, offer.sdp);
}

Expand All @@ -160,12 +161,12 @@ export class SendVideo {
if (this.pc.iceConnectionState !== 'closed') {
this.pc.close();
this.pc = null;
console.log('sending close message');
Logger.log('sending close message');
this.signaling.stop();
return;
}
}
console.log('peerConnection is closed.');
Logger.log('peerConnection is closed.');
await this.signaling.deleteConnection(this.connectionId);
this.connectionId = null;
}
Expand Down
6 changes: 4 additions & 2 deletions WebApp/public/js/gamepadEvents.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import * as Logger from "./logger.js";

const _e = 0.09;
const _gameloopInterval = 16.67; //in milliseconds, 60 times a second
var gameloop = null;
Expand Down Expand Up @@ -143,7 +145,7 @@ export function gamepadHandler(event, connecting) {
gamepadsConnectedTimeStamp[gamepad.index] = cookieTimeStamp;
}

console.log("connected: " + gamepadsConnectedTimeStamp[gamepad.index])
Logger.log("connected: " + gamepadsConnectedTimeStamp[gamepad.index])

} else {
delete gamepadsPreviousAxesStates[gamepad.index];
Expand All @@ -153,6 +155,6 @@ export function gamepadHandler(event, connecting) {
clearInterval(gameloop);
gameloop = null;
}
console.log("disconnected: " + gamepad.id)
Logger.log("disconnected: " + gamepad.id)
}
}
29 changes: 29 additions & 0 deletions WebApp/public/js/logger.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
let isDebug = false;

export function enable() {
isDebug = true;
}

export function disable() {
isDebug = false;
}

export function debug(msg) {
isDebug && console.debug(msg);
}

export function info(msg) {
isDebug && console.info(msg);
}

export function log(msg) {
isDebug && console.log(msg);
}

export function warn(msg) {
isDebug && console.warn(msg);
}

export function error(msg) {
isDebug && console.error(msg);
}
57 changes: 29 additions & 28 deletions WebApp/public/js/register-events.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { gamepadHandler } from "./gamepadEvents.js";
import * as Logger from "./logger.js";

const InputEvent = {
Keyboard: 0,
Expand Down Expand Up @@ -163,7 +164,7 @@ export function registerGamepadEvents(videoPlayer) {
const _videoPlayer = videoPlayer;

sendGamepadButtonDown = (e) => {
//console.log("gamepad id: " + e.id + " button index: " + e.index + " value " + e.value + " down" );
Logger.log("gamepad id: " + e.id + " button index: " + e.index + " value " + e.value + " down" );
let data = new DataView(new ArrayBuffer(19));
data.setUint8(0, InputEvent.Gamepad);
data.setUint8(1, GamepadEventType.ButtonDown);
Expand All @@ -174,7 +175,7 @@ export function registerGamepadEvents(videoPlayer) {
}

sendGamepadButtonUp = (e) => {
//console.log("gamepad id: " + e.id + " button index: " + e.index + " value " + e.value + " up" );
Logger.log("gamepad id: " + e.id + " button index: " + e.index + " value " + e.value + " up" );
let data = new DataView(new ArrayBuffer(19));
data.setUint8(0, InputEvent.Gamepad);
data.setUint8(1, GamepadEventType.ButtonUp);
Expand All @@ -185,7 +186,7 @@ export function registerGamepadEvents(videoPlayer) {
}

sendGamepadButtonPressed = (e) => {
//console.log("gamepad id: " + e.id + " button index: " + e.index + " value " + e.value + " pressed" );
Logger.log("gamepad id: " + e.id + " button index: " + e.index + " value " + e.value + " pressed" );
let data = new DataView(new ArrayBuffer(19));
data.setUint8(0, InputEvent.Gamepad);
data.setUint8(1, GamepadEventType.ButtonPressed);
Expand All @@ -196,7 +197,7 @@ export function registerGamepadEvents(videoPlayer) {
}

gamepadAxisChange = (e) => {
//console.log("gamepad id: " + e.id + " axis: " + e.index + " value " + e.value + " x:" + e.x + " y:" + e.y );
Logger.log("gamepad id: " + e.id + " axis: " + e.index + " value " + e.value + " x:" + e.x + " y:" + e.y );
let data = new DataView(new ArrayBuffer(27));
data.setUint8(0, InputEvent.Gamepad);
data.setUint8(1, GamepadEventType.Axis);
Expand Down Expand Up @@ -243,7 +244,7 @@ export function registerKeyboardEvents(videoPlayer) {
function sendKey(e, type) {
const key = Keymap[e.code];
const character = e.key.length === 1 ? e.key.charCodeAt(0) : 0;
//console.log("key down " + key + ", repeat = " + e.repeat + ", character = " + character);
Logger.log("key down " + key + ", repeat = " + e.repeat + ", character = " + character);
_videoPlayer && _videoPlayer.sendMsg(new Uint8Array([InputEvent.Keyboard, type, e.repeat, key, character]).buffer);
}

Expand All @@ -261,11 +262,11 @@ export function registerKeyboardEvents(videoPlayer) {
}


export function unregisterKeyboardEvents(videoPlayer) {

//Stop listening to keyboard events
document.removeEventListener('keyup', sendKeyUp, false);
document.removeEventListener('keydown', sendKeyDown, false);
export function unregisterKeyboardEvents(videoPlayer) {

//Stop listening to keyboard events
document.removeEventListener('keyup', sendKeyUp, false);
document.removeEventListener('keydown', sendKeyDown, false);
}


Expand Down Expand Up @@ -302,7 +303,7 @@ export function registerMouseEvents(videoPlayer, playerElement) {
}) === undefined ? PointerPhase.Stationary : phase;
}

//console.log("touch phase:" + phase + " length:" + changedTouches.length + " pageX" + changedTouches[0].pageX + ", pageX: " + changedTouches[0].pageY + ", force:" + changedTouches[0].force);
Logger.log("touch phase:" + phase + " length:" + changedTouches.length + " pageX" + changedTouches[0].pageX + ", pageX: " + changedTouches[0].pageY + ", force:" + changedTouches[0].force);

let data = new DataView(new ArrayBuffer(2 + 13 * touches.length));
data.setUint8(0, InputEvent.Touch);
Expand Down Expand Up @@ -363,7 +364,7 @@ export function registerMouseEvents(videoPlayer, playerElement) {
// const y = (e.clientY - originY) / scale;
const y = _videoPlayer.videoHeight - (e.clientY - originY) / scale;

//console.log("x: " + x + ", y: " + y + ", scale: " + scale + ", originX: " + originX + ", originY: " + originY + " mouse button:" + e.buttons);
Logger.log("x: " + x + ", y: " + y + ", scale: " + scale + ", originX: " + originX + ", originY: " + originY + " mouse button:" + e.buttons);
let data = new DataView(new ArrayBuffer(6));
data.setUint8(0, InputEvent.Mouse);
data.setInt16(1, x, true);
Expand All @@ -373,7 +374,7 @@ export function registerMouseEvents(videoPlayer, playerElement) {
}

function sendMouseWheel(e) {
//console.log("mouse wheel with delta " + e.wheelDelta);
Logger.log("mouse wheel with delta " + e.wheelDelta);
let data = new DataView(new ArrayBuffer(9));
data.setUint8(0, InputEvent.MouseWheel);
data.setFloat32(1, e.deltaX, true);
Expand All @@ -400,21 +401,21 @@ export function registerMouseEvents(videoPlayer, playerElement) {
}


export function unregisterMouseEvents(videoPlayer, playerElement) {

// Stop listening to mouse events
playerElement.removeEventListener('click', sendMouse, false);
playerElement.removeEventListener('mousedown', sendMouse, false);
playerElement.removeEventListener('mouseup', sendMouse, false);
playerElement.removeEventListener('mousemove', sendMouse, false);
playerElement.removeEventListener('wheel', sendMouseWheel, false);

// Stop listening to touch events based on "Touch Events Level1" TR.
playerElement.removeEventListener('touchend', sendTouchEnd, false);
playerElement.removeEventListener('touchstart', sendTouchStart, false);
playerElement.removeEventListener('touchcancel', sendTouchCancel, false);
playerElement.removeEventListener('touchmove', sendTouchMove, false);

export function unregisterMouseEvents(videoPlayer, playerElement) {

// Stop listening to mouse events
playerElement.removeEventListener('click', sendMouse, false);
playerElement.removeEventListener('mousedown', sendMouse, false);
playerElement.removeEventListener('mouseup', sendMouse, false);
playerElement.removeEventListener('mousemove', sendMouse, false);
playerElement.removeEventListener('wheel', sendMouseWheel, false);

// Stop listening to touch events based on "Touch Events Level1" TR.
playerElement.removeEventListener('touchend', sendTouchEnd, false);
playerElement.removeEventListener('touchstart', sendTouchStart, false);
playerElement.removeEventListener('touchcancel', sendTouchCancel, false);
playerElement.removeEventListener('touchmove', sendTouchMove, false);

}


Expand Down
26 changes: 14 additions & 12 deletions WebApp/public/js/signaling.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import * as Logger from "./logger.js";

export default class Signaling extends EventTarget {

constructor() {
Expand Down Expand Up @@ -38,7 +40,7 @@ export default class Signaling extends EventTarget {

const data = await res.json();
const offers = data.offers;
console.log('get offers:', offers);
logger.log('get offers:', offers);

offers.forEach(offer => {
this.dispatchEvent(new CustomEvent('offer', { detail: offer }));
Expand All @@ -58,7 +60,7 @@ export default class Signaling extends EventTarget {

const data = await res.json();
const answers = data.answers;
console.log('get answers:', answers);
Logger.log('get answers:', answers);

answers.forEach(answer => {
this.dispatchEvent(new CustomEvent('answer', { detail: answer }));
Expand All @@ -78,7 +80,7 @@ export default class Signaling extends EventTarget {

const data = await res.json();
const candidates = data.candidates;
console.log('get candidates:', candidates);
Logger.log('get candidates:', candidates);

if (candidates.length > 0) {
for (let candidate of candidates[0].candidates) {
Expand Down Expand Up @@ -112,13 +114,13 @@ export default class Signaling extends EventTarget {

async sendOffer(connectionId, sdp) {
const data = { 'sdp': sdp, 'connectionId': connectionId };
console.log('sendOffer:', data);
Logger.log('sendOffer:', data);
await fetch(this.url('offer'), { method: 'POST', headers: this.headers(), body: JSON.stringify(data) });
};

async sendAnswer(connectionId, sdp) {
const data = { 'sdp': sdp, 'connectionId': connectionId };
console.log('sendAnswer:', data);
Logger.log('sendAnswer:', data);
await fetch(this.url('answer'), { method: 'POST', headers: this.headers(), body: JSON.stringify(data) });
};

Expand All @@ -129,7 +131,7 @@ export default class Signaling extends EventTarget {
'sdpMid': sdpMid,
'connectionId': connectionId
};
console.log('sendCandidate:', data);
Logger.log('sendCandidate:', data);
await fetch(this.url('candidate'), { method: 'POST', headers: this.headers(), body: JSON.stringify(data) });
};

Expand Down Expand Up @@ -173,7 +175,7 @@ export class WebSocketSignaling extends EventTarget {
return;
}

console.log(msg);
Logger.log(msg);

switch (msg.type) {
case "connect":
Expand Down Expand Up @@ -212,27 +214,27 @@ export class WebSocketSignaling extends EventTarget {

createConnection(connectionId) {
const sendJson = JSON.stringify({ type: "connect", connectionId: connectionId });
console.log(sendJson);
Logger.log(sendJson);
this.websocket.send(sendJson);
};

deleteConnection(connectionId) {
const sendJson = JSON.stringify({ type: "disconnect", connectionId: connectionId });
console.log(sendJson);
Logger.log(sendJson);
this.websocket.send(sendJson);
};

sendOffer(connectionId, sdp) {
const data = { 'sdp': sdp, 'connectionId': connectionId };
const sendJson = JSON.stringify({ type: "offer", from: connectionId, data: data });
console.log(sendJson);
Logger.log(sendJson);
this.websocket.send(sendJson);
}

sendAnswer(connectionId, sdp) {
const data = { 'sdp': sdp, 'connectionId': connectionId };
const sendJson = JSON.stringify({ type: "answer", from: connectionId, data: data });
console.log(sendJson);
Logger.log(sendJson);
this.websocket.send(sendJson);
}

Expand All @@ -244,7 +246,7 @@ export class WebSocketSignaling extends EventTarget {
'connectionId': connectionId
};
const sendJson = JSON.stringify({ type: "candidate", from: connectionId, data: data });
console.log(sendJson);
Logger.log(sendJson);
this.websocket.send(sendJson);
}
}
Loading

0 comments on commit fc99f34

Please sign in to comment.