From 78c127ad4dfa1c36b7f802e3890e21b3b78897b9 Mon Sep 17 00:00:00 2001 From: Jimmy Huang Date: Fri, 13 Sep 2013 16:55:21 -0700 Subject: [PATCH] Code refactoring and cleanup Change-Id: Ib6b5018442cd35b585d7d899f952cc4d4e5bf9da Signed-off-by: Jimmy Huang --- css/style.css | 3 + index.html | 4 +- js/api-bluetooth.js | 34 +++++----- js/main.js | 32 ++++----- js/panel-bluetooth.js | 81 +++++++++++----------- js/utils.js | 39 +++++------ js/websocket.js | 183 ++++++++++++++++++++++++++------------------------ 7 files changed, 198 insertions(+), 178 deletions(-) diff --git a/css/style.css b/css/style.css index 859ed88..8f140f1 100644 --- a/css/style.css +++ b/css/style.css @@ -46,6 +46,9 @@ margin-bottom: 100px; } /* Bluetooth */ +#bluetooth_devices { + display: none; +} .device-paired .device-status { color: green; } diff --git a/index.html b/index.html index c3f7f61..4bd605a 100644 --- a/index.html +++ b/index.html @@ -71,8 +71,8 @@

Available Devices

-
    -
      +
        +
          Scan
          diff --git a/js/api-bluetooth.js b/js/api-bluetooth.js index 592882b..37efbed 100644 --- a/js/api-bluetooth.js +++ b/js/api-bluetooth.js @@ -14,8 +14,8 @@ settings.bluetooth = settings.bluetooth || {}; /* Module */ settings.bluetooth = (function() { - var default_adapter = null; - + var default_adapter = null; + /* Adapter class */ var BluetoothAdapter = function(adapter) { this.bt_adapter = adapter; @@ -31,19 +31,19 @@ settings.bluetooth = (function() { if (powered) { // Power on this.bt_adapter.setPowered(true, function() { - self.powered = self.bt_adapter.powered; + self.powered = self.bt_adapter.powered; success_cb(); - }, function (e) { - self.powered = self.bt_adapter.powered; + }, function(e) { + self.powered = self.bt_adapter.powered; error_cb(e); }); } else { // Power off this.bt_adapter.setPowered(false, function() { - self.powered = self.bt_adapter.powered; + self.powered = self.bt_adapter.powered; success_cb(); - }, function (e) { - self.powered = self.bt_adapter.powered; + }, function(e) { + self.powered = self.bt_adapter.powered; error_cb(e); }); } @@ -110,21 +110,21 @@ settings.bluetooth = (function() { } function subscribeEvents(event_callback) { - wsAPI.subscribeEvents(event_callback); + wsAPI.subscribeEvents(event_callback); } - + function unsubscribeEvents(event_callback) { - wsAPI.unsubscribeEvents(event_callback); + wsAPI.unsubscribeEvents(event_callback); } function getDefaultAdapter() { try { - if (tizen.bluetooth.getDefaultAdapter() == null) - return null; - else if (default_adapter == null) { - default_adapter = new BluetoothAdapter(tizen.bluetooth.getDefaultAdapter()); - } - return default_adapter; + if (tizen.bluetooth.getDefaultAdapter() == null) { + return null; + } else if (default_adapter == null) { + default_adapter = new BluetoothAdapter(tizen.bluetooth.getDefaultAdapter()); + } + return default_adapter; } catch (e) { console.error('Tizen web api missing'); return null; diff --git a/js/main.js b/js/main.js index 3c8c8f1..bc4c58c 100644 --- a/js/main.js +++ b/js/main.js @@ -11,6 +11,21 @@ function connected() { console.log('Settings daemon connected'); + } + + function disconnected(e) { + console.log('Settings daemon disconnected...'); + showMsg('Error', e); + } + + function init() { + console.log('Settings init...'); + $('#quit').on('click', function() { + console.log('Settings exiting...'); + tizen.application.getCurrentApplication().exit(); + }); + + wsAPI.connect('ws://localhost:16000/', 'http-only', connected, disconnected); try { /* Settings Panel */ @@ -22,25 +37,10 @@ /* Different sub panels */ bluetoothPanelInit(); } catch (e) { - showMsg('Error', 'Javascript Exception Caught'); - console.log('Error - javascript exception caught: ' + e); + showMsg('Error', 'Javascript Exception Caught: ' + e); } } - function disconnected() { - console.log('Settings daemon disconnected'); - } - - function init() { - console.log('init() called'); - $('#quit').on('click', function() { - console.log('exiting...'); - tizen.application.getCurrentApplication().exit(); - }); - - wsAPI.connect('ws://localhost:16000/settings', 'http-only', connected, disconnected); - } - $(document).ready(function() { init(); }) diff --git a/js/panel-bluetooth.js b/js/panel-bluetooth.js index 26bdab6..b8fec51 100644 --- a/js/panel-bluetooth.js +++ b/js/panel-bluetooth.js @@ -9,7 +9,7 @@ function bluetoothPanelInit() { - settings.bluetooth.subscribeEvents(bluetoothEventReceived); + settings.bluetooth.subscribeEvents(bluetoothEventReceived); /* Bluetooth Settings Panel */ $('#page_bluetooth').on('pageshow', function(event, data) { @@ -17,8 +17,8 @@ function bluetoothPanelInit() { var adapter = settings.bluetooth.getDefaultAdapter(); if (adapter === null) { - showMsg('Error', 'Bluetooth adapter not found'); - return; + showMsg('Error', 'Bluetooth adapter not found'); + return; } console.log('Default BT adapter: ', adapter.name); @@ -40,7 +40,7 @@ function bluetoothPanelInit() { var bt_switch = $(this); var adapter = settings.bluetooth.getDefaultAdapter(); if (adapter === null) { - showMsg('Error', 'Bluetooth adapter not found'); + showMsg('Error', 'Bluetooth adapter not found'); bluetoothToggleOff(); return; } @@ -94,8 +94,8 @@ function bluetoothPanelInit() { $('#button_bluetooth_scan').on('click', function() { var adapter = settings.bluetooth.getDefaultAdapter(); if (adapter === null) { - showMsg('Error', 'Bluetooth adapter not found'); - return; + showMsg('Error', 'Bluetooth adapter not found'); + return; } if ($('#button_bluetooth_scan').text() === 'Scan') { bluetoothStartScan(adapter); @@ -115,12 +115,12 @@ function bluetoothPanelInit() { } function bluetoothEventReceived(event) { - if (event.type !== WS_EVENT_TYPE.BLUETOOTH) return; - console.log('Bluetooth event received: [' + event.name + ', ' + event.value + ']'); + if (event.type !== WS_EVENT_TYPE.BLUETOOTH) return; + console.log('Bluetooth event received: [' + event.name + ', ' + event.value + ']'); } function bluetoothClearAvailableList() { - $('#listview_bluetooth_available').html(''); + $('#listview_device_available').html(''); } function bluetoothStartScan(adapter) { @@ -152,13 +152,13 @@ function bluetoothStartScan(adapter) { } }, function(e) { /* error */ - showMsg('Error', 'Cannot scan: ' + e); + showMsg('Error', 'Cannot scan: ' + e); }); } function bluetoothRefreshList() { - $('#listview_bluetooth_paired').listview('refresh'); - $('#listview_bluetooth_available').listview('refresh'); + $('#listview_device_paired').listview('refresh'); + $('#listview_device_available').listview('refresh'); } function bluetoothStopScan(adapter) { @@ -174,16 +174,16 @@ function bluetoothStopScan(adapter) { function bluetoothAppendToPairedList(device) { console.log('Append to paired list - ' + device.address); - if ($('#listview_bluetooth_paired').find(jqId(device.address)).length != 0) return; + if ($('#listview_device_paired').find(jqId(device.address)).length != 0) return; - var parent = '#listview_bluetooth_paired'; + var parent = '#listview_device_paired'; bluetoothConstructDeviceElement(parent, device); bluetoothUpdateDeviceButton(device); bluetoothRefreshList(); } function bluetoothRemoveFromPairedList(device_addr) { - var removeThis = $('#listview_bluetooth_paired li').filter(function() { + var removeThis = $('#listview_device_paired li').filter(function() { return $(this).find(jqId(device_addr)).length === 1; }); @@ -196,16 +196,16 @@ function bluetoothRemoveFromPairedList(device_addr) { function bluetoothAppendToAvailableList(device) { console.log('Append to available list - ' + device.address); - if ($('#listview_bluetooth_available').find(jqId(device.address)).length != 0) return; + if ($('#listview_device_available').find(jqId(device.address)).length != 0) return; - var parent = '#listview_bluetooth_available'; + var parent = '#listview_device_available'; bluetoothConstructDeviceElement(parent, device); bluetoothUpdateDeviceButton(device); bluetoothRefreshList(); } function bluetoothRemoveFromAvailableList(device_addr) { - var removeThis = $('#listview_bluetooth_available li').filter(function() { + var removeThis = $('#listview_device_available li').filter(function() { return $(this).find(jqId(device_addr)).length === 1; }); @@ -217,17 +217,18 @@ function bluetoothRemoveFromAvailableList(device_addr) { } function bluetoothConstructDeviceElement(parent, device) { - var html = '
        • ' + - '' + - '
          ' + device.name + '
          ' + - '
          ' + device.address + '
          ' + - '
          ' + - '
          ' + - '
        • '; + var html = '
        • '; + html += ''; + html += '
          ' + device.name + '
          '; + html += '
          ' + device.address + '
          '; + html += '
          '; + html += '
          '; + html += '
        • '; $(parent).append(html).trigger('create'); /* store device object in the element so we can reference it later */ $(jqId(device.address)).data('device-object', device); + console.log('Storing device object: ' + jqId(device.address)); $(jqId(device.address)).on('click', function() { localStorage.setItem('bluetooth_device_id', device.address); @@ -236,13 +237,17 @@ function bluetoothConstructDeviceElement(parent, device) { $(jqId(device.address)).find('div.device-action-button').on('click', function(e) { var parent = $(this).parent().attr('id'); + console.log('device action button clicked'); - /* prevent the click event to propagate up to trigger the device info button click */ + /* + * prevent the click event to propagate up + */ e.stopImmediatePropagation(); e.preventDefault(); var adapter = settings.bluetooth.getDefaultAdapter(); if (adapter === null) return; + /* retrieve the device object from element */ var device = $(jqId(parent)).data('device-object'); if (device == undefined) { @@ -251,7 +256,7 @@ function bluetoothConstructDeviceElement(parent, device) { } if (!device.paired) { - createPopupDialog(false, false, 'Pair with ' + device.name, 'Blueotooth address: ' + device.address, 'Pair', 'Cancel', function() { + createPopupDialog(false, false, 'Pair with', device.name, 'Pair', 'Cancel', function() { console.log('Bluetooth pair with device: ' + device.address); showSpinner(false, 'Pairing...'); adapter.pairDevice(device.address, function() { @@ -259,7 +264,7 @@ function bluetoothConstructDeviceElement(parent, device) { hideSpinner(); device.paired = true; - /* changing from unpaired to paired, move to the paired list by reconstructing */ + /* changing from unpaired to paried */ bluetoothUpdateDevice(device); }, function(e) { /* error */ @@ -347,12 +352,12 @@ function bluetoothConstructDetailPanel(device) { if (device.connected) status_connected = 'Yes'; $('#page_bluetooth_detail_content').html(''); - var html = ''; + var html = ''; $('#page_bluetooth_detail_content').append(html).trigger('create'); if (device.paired) { @@ -364,9 +369,9 @@ function bluetoothConstructDetailPanel(device) { var adapter = settings.bluetooth.getDefaultAdapter(); if (adapter === null) return; - createPopupDialog(false, false, 'Unpair with ' + device.name, 'Blueotooth address: ' + device.address, 'Unpair', 'Cancel', function() { - showSpinner(false, 'Unpairing...'); - adapter.unpairDevice(device.address, function() { + createPopupDialog(false, false, 'Unpair with device', device.name, 'Unpair', 'Cancel', function() { + showSpinner(false, 'Unpairing...'); + adapter.unpairDevice(device.address, function() { /* success */ hideSpinner(); device.paired = false; @@ -384,7 +389,7 @@ function bluetoothConstructDetailPanel(device) { showMsg('Error', 'Bluetooth unpair failed: ' + e); /* Something is wrong, remove from paired list */ - bluetoothRemoveFromPairedList(device); + bluetoothRemoveFromPairedList(device.address); }); }); }); diff --git a/js/utils.js b/js/utils.js index b050b41..4c50a77 100644 --- a/js/utils.js +++ b/js/utils.js @@ -9,21 +9,22 @@ function jqId(id) { if (id == undefined) return null; - return '#' + id.replace(/(:|\.)/g, '\\$1'); + + /* replace colons and spaces with dash for jquery ids */ + return '#' + id.replace(/:| /g, '-'); } function showMsg(title, message) { - if (title == 'Error') { - console.error(message); - } - else { - console.log(message); - } + if (title == 'Error') { + console.error(message); + } else { + console.log(message); + } createPopupDialog(true, false, title, message); } function showInputDialog(title, input_message, ok_button_text, cancel_button_text, ok_callback) { - createPopupDialog(false, true, title, input_message, ok_button_text, cancel_button_text, ok_callback); + createPopupDialog(false, true, title, input_message, ok_button_text, cancel_button_text, ok_callback); } function createPopupDialog(dismiss, is_input, title, message, ok_button_text, cancel_button_text, ok_callback) { @@ -41,11 +42,11 @@ function createPopupDialog(dismiss, is_input, title, message, ok_button_text, ca }).appendTo($dialog); if (is_input) { - + } else { - $('

          ', { - text: message - }).appendTo($dialog); + $('

          ', { + text: message + }).appendTo($dialog); } $('', { @@ -55,13 +56,13 @@ function createPopupDialog(dismiss, is_input, title, message, ok_button_text, ca }).on('click', function() { $dialog.popup('close'); if (ok_callback) { - if (is_input) { - /* TODO implement getting input from field */ - ok_callback(); - - } else { - ok_callback(); - } + if (is_input) { + /* TODO implement getting input from field */ + ok_callback(); + + } else { + ok_callback(); + } } }).appendTo($dialog); diff --git a/js/websocket.js b/js/websocket.js index 68b704d..098dea4 100644 --- a/js/websocket.js +++ b/js/websocket.js @@ -11,32 +11,32 @@ var dummyBackend = true; var WS_REQUEST_TYPE = { - WIFI : 0, - BLUETOOTH : 1, - DISPLAY : 2, - SOUND: 3, - DATETIME: 4, - LOCALE: 5 - }; + WIFI: 0, + BLUETOOTH: 1, + DISPLAY: 2, + SOUND: 3, + DATETIME: 4, + LOCALE: 5 +}; var WS_EVENT_TYPE = { - WIFI : 0, - BLUETOOTH : 1, - DISPLAY : 2, - SOUND: 3, - DATETIME: 4, - LOCALE: 5 - }; + WIFI: 0, + BLUETOOTH: 1, + DISPLAY: 2, + SOUND: 3, + DATETIME: 4, + LOCALE: 5 +}; /* web socket module to connect to the settings daemon */ var wsAPI = (function() { /* number of connection retries to attempt if the socket closes */ var self = this; this.connected = false; - this.event_callbacks = $.Callbacks(); + this.event_callbacks = $.Callbacks(); /* default values for WebSocket */ - this.socketUrl = 'ws://localhost:16000/settings'; + this.socketUrl = 'ws://localhost:16000/'; this.socketProtocol = 'http-only'; this.methodIdx = 0; @@ -67,12 +67,12 @@ var wsAPI = (function() { me.done = true; } } - + this.EventObject = function(type, name, value) { - var me = this; - this.type = type; - this.name = name; - this.value = value; + var me = this; + this.type = type; + this.name = name; + this.value = value; } function connect(url, protocol, sucess_cb, error_cb) { @@ -87,27 +87,41 @@ var wsAPI = (function() { } else { self.socket = new WebSocket(self); } + console.log('Connecting to websocket: ' + self.socketUrl); self.socket.onopen = function() { self.connected = true; - console.log('socket opened'); + console.log('websocket opened'); self.successCB(); }; self.socket.onclose = function() { self.connected = false; - console.log('socket closed'); + console.log('websocket closed'); if (dummyBackend) { - /* fake the connection for now */ + /* fake the connection for dummy backend */ self.connected = true; self.successCB(); + return; } + + self.errorCB('Disconnected from settings daemon'); }; self.socket.onerror = function(e) { - console.log('socket error: ', e.data); - self.errorCB(); + console.log('web socket error: ', e.data); + + if (dummyBackend) { + /* ignore websocket error */ + return; + } + + if (e.data) { + self.errorCB('websocket error: ' + e.data); + } else { + self.errorCB('websocket error: unknown'); + } }; self.socket.onmessage = function(e) { @@ -121,7 +135,7 @@ var wsAPI = (function() { function send(msg, success_cb, error_cb) { if (!this.connected) { if (errorCB !== undefined) { - errorCB('\"' + obj.name + '\" method failed because socket is closed'); + errorCB('Settings daemon is not connected'); } return; } @@ -129,25 +143,28 @@ var wsAPI = (function() { this.methodIdx = (this.methodIdx + 1) % 100; this.methodCalls[i] = new this.MethodCall(msg.transactionid, msg.name, success_cb, error_cb); this.methodCalls[i].start(); - console.log('methodCalls[', i, '].start()'); + + var jsonMsg = JSON.stringify(msg); + console.log('Sending json msg: ' + jsonMsg); if (dummyBackend) { /* fake with dummy data */ dummyBackendSend(msg); } else { - this.socket.send(JSON.stringify(msg)); + this.socket.send(jsonMsg); } } function fireEvent(type, name, value) { - var event = new this.EventObject(type, name, value); - console.log('Fire event: [' + type + ', ' + name + ', ' + value + ']'); - event_callbacks.fire(event); + var event = new this.EventObject(type, name, value); + console.log('Fire event: [' + type + ', ' + name + ', ' + value + ']'); + event_callbacks.fire(event); } function receive(msg) { var self = this; var event; try { + console.log("Received json msg: " + msg); event = JSON.parse(msg); } catch (e) { self.iErrorCB('GARBAGE MESSAGE: ' + msg); @@ -164,7 +181,6 @@ var wsAPI = (function() { var call = calls[i]; if (call && (!call.done) && (call.transactionid === event.transactionid)) { call.finish(); - console.log('methodCalls[', i, '].finish()'); if (event.error !== undefined) { call.errorCB(event.error); } @@ -174,9 +190,8 @@ var wsAPI = (function() { return; } } - } - else if (event.type === 'event') { - self.fireSevent(event.name, event.data); + } else if (event.type === 'event') { + self.fireSevent(event.name, event.data); } } } @@ -199,18 +214,15 @@ var wsAPI = (function() { 'data': request_args }; - console.log('wsAPI.sendRequest(): ', request_type); - console.log('request name: ', request_name); - console.log('request args: ', request_args); send(msg, success_cb, error_cb); } - + function subscribeEvents(callback) { - event_callbacks.add(callback); + event_callbacks.add(callback); } - + function unsubscribeEvents(callback) { - event_callbacks.remove(callback); + event_callbacks.remove(callback); } /* this is dummy data for testing purposes */ @@ -218,49 +230,48 @@ var wsAPI = (function() { if (dummyBackend) { console.log('Sending to dummy server'); - var calls = this.methodCalls; - var replyMsg = null; - - for (var i = 0; i < calls.length; i++) { - var call = calls[i]; - if (call && (!call.done) && (call.transactionid === msg.transactionid)) { - call.finish(); - console.log('methodCalls[', i, '].finish()'); - if (msg.error !== undefined) { - call.errorCB(msg.error); - } - if (msg.data !== undefined && call.successCB && call.errorCB !== undefined) { - console.log('Send request to dummy backend: type - ', msg.type); - console.log('Send request to dummy backend: name - ', msg.name); - console.log('Send request to dummy backend: args - ', msg.data); - switch(msg.type) - { - case WS_REQUEST_TYPE.BLUETOOTH: - if (msg.name === 'enable') { - fireEvent(WS_EVENT_TYPE.BLUETOOTH, 'enabled', true); - } else if (msg.name === 'disable') { - fireEvent(WS_EVENT_TYPE.BLUETOOTH, 'enabled', false); - } - else { - call.errorCB('Unsupported request name: ' + msg.name); - return; - } - break; - case WS_REQUEST_TYPE.WIFI: - case WS_REQUEST_TYPE.DISPLAY: - case WS_REQUEST_TYPE.SOUND: - case WS_REQUEST_TYPE.DATETIME: - case WS_REQUEST_TYPE.LOCALE: - call.errorCB('Request not implemented'); - return; - default: - call.errorCB('Invalid request type: ' + msg.type); - return; - } - call.successCB(replyMsg); - } - return; - } + var calls = this.methodCalls; + var replyMsg = null; + + for (var i = 0; i < calls.length; i++) { + var call = calls[i]; + if (call && (!call.done) && (call.transactionid === msg.transactionid)) { + call.finish(); + if (msg.error !== undefined) { + call.errorCB(msg.error); + } + if (msg.data !== undefined && call.successCB && call.errorCB !== undefined) { + var replyDelay = 0; + + switch (msg.type) { + case WS_REQUEST_TYPE.WIFI: + case WS_REQUEST_TYPE.BLUETOOTH: + if (msg.name === 'enable') { + fireEvent(WS_EVENT_TYPE.BLUETOOTH, 'enabled', true); + } else if (msg.name === 'disable') { + fireEvent(WS_EVENT_TYPE.BLUETOOTH, 'enabled', false); + } else { + call.errorCB('Unsupported request name: ' + msg.name); + return; + } + break; + case WS_REQUEST_TYPE.WIFI: + case WS_REQUEST_TYPE.DISPLAY: + case WS_REQUEST_TYPE.SOUND: + case WS_REQUEST_TYPE.DATETIME: + case WS_REQUEST_TYPE.LOCALE: + call.errorCB('Request not implemented'); + return; + default: + call.errorCB('Invalid request type: ' + msg.type); + return; + } + setTimeout(function() { + call.successCB(replyMsg); + }, replyDelay); + } + return; + } } } } -- 2.7.4