Skip to content
Browse files

Merge pull request #7423 from lodr/fix-reset-squashed

Bug 825192 - Reset fixed for WiFi and mobile usage.
  • Loading branch information...
2 parents 6c08e45 + e3eb071 commit b9c5d81b69bc065c637926ced8d6262a4c18edaa @vingtetun vingtetun committed
View
27 apps/costcontrol/js/app.js
@@ -13,8 +13,29 @@ var CostControlApp = (function() {
var costcontrol, initialized = false;
window.addEventListener('DOMContentLoaded', function _onDOMReady() {
- checkSIMChange();
+ var mobileConnection = window.navigator.mozMobileConnection;
+
+ // No SIM
+ if (!mobileConnection || mobileConnection.cardState === 'absent') {
+ //TODO: Add a message saying there is no functionality when no SIM
+ // then close
+ window.close();
+ return;
+
+ // SIM is not ready
+ } else if (mobileConnection.cardState !== 'ready') {
+ debug('SIM not ready:', mobileConnection.cardState);
+ mobileConnection.oniccinfochange = _onDOMReady;
+
+ // SIM is ready
+ } else {
+ mobileConnection.oniccinfochange = undefined;
+ _startApp();
+ }
+ });
+ function _startApp() {
+ checkSIMChange();
CostControl.getInstance(function _onCostControlReady(instance) {
if (ConfigManager.option('fte')) {
window.location = '/fte.html';
@@ -23,7 +44,7 @@ var CostControlApp = (function() {
costcontrol = instance;
setupApp();
});
- });
+ }
window.addEventListener('localized', function _onLocalize() {
if (initialized)
@@ -93,7 +114,7 @@ var CostControlApp = (function() {
function updateUI() {
ConfigManager.requestSettings(function _onSettings(settings) {
var mode = costcontrol.getApplicationMode(settings);
- debug('App UI mode: ' + mode);
+ debug('App UI mode: ', mode);
// Layout
if (mode !== currentMode) {
View
29 apps/costcontrol/js/common.js
@@ -75,14 +75,14 @@ function resetData() {
// Get current mobile data
var now = new Date();
- var request = window.navigator.mozNetworkStats.getNetworkStats({
+ var mobileRequest = window.navigator.mozNetworkStats.getNetworkStats({
start: now,
end: now,
connectionType: 'mobile'
});
- request.onsuccess = function _onMobileForToday() {
- var data = request.result.data;
- debug('Data length should be 1 and it is ' + data.length);
+ mobileRequest.onsuccess = function _onMobileForToday() {
+ var data = mobileRequest.result.data;
+ debug('Data length should be 1 and it is', data.length);
var currentDataUsage = 0;
if (data[0].rxBytes)
currentDataUsage += data[0].rxBytes;
@@ -91,7 +91,7 @@ function resetData() {
// Adds the fixing
var tag = tags[tags.length - 1];
- tag.fixing = currentDataUsage;
+ tag.fixing.push([now, currentDataUsage]);
// Remove the previous ones
for (var i = tags.length - 2; i >= 0; i--) {
@@ -99,12 +99,29 @@ function resetData() {
if (ctag.sim === tag.sim)
tags.splice(i, 1);
}
- debug('After reset ' + JSON.stringify(tags));
+ debug('After reset', tags);
asyncStorage.setItem('dataUsageTags', tags, function _done() {
ConfigManager.setOption({ lastDataReset: now });
});
};
+
+ var wifiRequest = window.navigator.mozNetworkStats.getNetworkStats({
+ start: now,
+ end: now,
+ connectionType: 'wifi'
+ });
+ wifiRequest.onsuccess = function _onWiFiForToday() {
+ var data = wifiRequest.result.data;
+ debug('Data length should be 1 and it is', data.length);
+ var currentWifiUsage = 0;
+ if (data[0].rxBytes)
+ currentWifiUsage += data[0].rxBytes;
+ if (data[0].txBytes)
+ currentWifiUsage += data[0].txBytes;
+ ConfigManager.setOption({ wifiFixing: currentWifiUsage });
+ };
+
});
}
View
24 apps/costcontrol/js/config_manager.js
@@ -44,7 +44,8 @@ var ConfigManager = (function() {
'nextReset': null,
'plantype': 'prepaid',
'resetTime': 1,
- 'trackingPeriod': 'never'
+ 'trackingPeriod': 'never',
+ 'wifiFixing': 0
};
// Load the vendor configuration provided in <GAIA>/build/application-data.js
@@ -89,24 +90,23 @@ var ConfigManager = (function() {
return new Date(v['__date__']);
}
- var currentICCID = 'NOICCID';
- if ('mozMobileConnection' in window.navigator) {
- currentICCID = window.navigator.mozMobileConnection.iccInfo.iccid || 'NOICCID';
- }
-
// Load stored settings
+ var NO_ICCID = 'NOICCID';
var settings;
function requestSettings(callback) {
+ var currentICCID = window.navigator.mozMobileConnection.iccInfo.iccid ||
+ NO_ICCID;
asyncStorage.getItem(currentICCID, function _wrapGetItem(localSettings) {
// No entry: set defaults
try {
settings = JSON.parse(localSettings, settingsReviver);
- } catch(e) {
+ } catch (e) {
// If we can't parse the settings, use the default ones
}
if (settings === null) {
settings = deepCopy(DEFAULT_SETTINGS);
+ debug('Storing default settings for ICCID:', currentICCID);
asyncStorage.setItem(currentICCID, JSON.stringify(settings));
}
@@ -135,7 +135,7 @@ var ConfigManager = (function() {
settings: settings
} });
window.dispatchEvent(event);
- debug('Event optionchange dispatched for ' + name);
+ debug('Event optionchange dispatched for', name);
}
// Set setting options asynchronously and dispatch an event for every
@@ -159,6 +159,8 @@ var ConfigManager = (function() {
}
// Set items and dispatch the events
+ var currentICCID = window.navigator.mozMobileConnection.iccInfo.iccid ||
+ NO_ICCID;
asyncStorage.setItem(currentICCID, JSON.stringify(settings),
function _onSet() {
requestSettings(function _onSettings(settings) {
@@ -189,7 +191,7 @@ var ConfigManager = (function() {
var callbacks;
// Function in charge of dispatch the events to the observers
function callCallbacks(evt) {
- debug('Option ' + evt.detail.name + ' has changed!');
+ debug('Option', evt.detail.name, 'has changed!');
var callbackCollection = callbacks[evt.detail.name] || [];
for (var i = 0, callback; callback = callbackCollection[i]; i++) {
callback(evt.detail.value, evt.detail.oldValue, evt.detail.name,
@@ -201,7 +203,7 @@ var ConfigManager = (function() {
// an initial call to the callback unless you provide true as the last
// parameter.
function syncObserve(name, callback, avoidInitialCall) {
- debug('Installing observer for ' + name);
+ debug('Installing observer for', name);
// XXX: initialize this only if an observer is added
if (callbacks === undefined) {
@@ -215,7 +217,7 @@ var ConfigManager = (function() {
if (evt.key === 'sync') {
var name = evt.newValue.split('#')[0];
var oldValue = settings ? settings[name] : undefined;
- debug('Synchronization request for ' + name + ' received!');
+ debug('Synchronization request for', name, 'received!');
requestSettings(function _onSettings(newSettings) {
settings = newSettings;
dispatchOptionChange(name, settings[name], oldValue, settings);
View
28 apps/costcontrol/js/costcontrol.js
@@ -80,7 +80,7 @@ var CostControl = (function() {
// specific handler.
function request(requestObj, callback) {
ConfigManager.requestAll(function _onInfo(configuration, settings) {
- debug('Request for: ' + requestObj.type);
+ debug('Request for:', requestObj.type);
var force = requestObj.force;
var result = {};
@@ -228,8 +228,7 @@ var CostControl = (function() {
newAlarm.onsuccess = function _alarmSet(evt) {
var id = evt.target.result;
- debug('Timeout for balance (' + id +
- ') update set to: ' + BALANCE_TIMEOUT);
+ debug('Timeout for balance (', id, ') update set to:', BALANCE_TIMEOUT);
ConfigManager.setOption(
{
@@ -264,7 +263,7 @@ var CostControl = (function() {
// Send a top up SMS and set timeouts for interrupting waiting for response
var TOPUP_TIMEOUT = 5 * 60 * 1000; // Should be 5 min
function requestTopUp(configuration, settings, code, callback, result) {
- debug('Requesting TopUp with code ' + code + '...');
+ debug('Requesting TopUp with code', code, '...');
// TODO: Ensure is free
var newSMS = sms.send(
@@ -280,8 +279,7 @@ var CostControl = (function() {
newAlarm.onsuccess = function _alarmSet(evt) {
var id = evt.target.result;
- debug('Timeout for TopUp (' + id +
- ') update set to: ' + TOPUP_TIMEOUT);
+ debug('Timeout for TopUp (', id, ') update set to:', TOPUP_TIMEOUT);
// XXX: waitingForTopUp can be null if no waiting or distinct
// than null to indicate the unique id of the timeout waiting
@@ -321,9 +319,9 @@ var CostControl = (function() {
debug('Statistics out of date. Requesting fresh data...');
// If settings.lastDataReset is not set let's use the past week. This is
- // only for not breaking dogfooders build and this can be remove at some point
- // in the future (and since this sentence has been said multiple times this
- // code will probably stay here for a while).
+ // only for not breaking dogfooders build and this can be remove at some
+ // point in the future (and since this sentence has been said multiple times
+ // this code will probably stay here for a while).
var start = toMidnight(new Date(settings.lastDataReset ||
Date.now() - 7 * DAY));
@@ -357,10 +355,13 @@ var CostControl = (function() {
// Finally, store the result and continue
mobileRequest.onsuccess = function _onMobileData() {
- var wifiData = adaptData(wifiRequest.result);
- debug('WIFI: ' + JSON.stringify(wifiData));
+ var fakeTag = {
+ sim: connection.iccInfo.iccid,
+ start: settings.lastDataReset,
+ fixing: [[settings.lastDataReset, settings.wifiFixing || 0]]
+ };
+ var wifiData = adaptData(wifiRequest.result, [fakeTag]);
var mobileData = adaptData(mobileRequest.result, tags);
- debug('MOBILE: ' + JSON.stringify(mobileData));
var lastDataUsage = {
timestamp: new Date() ,
start: start,
@@ -375,7 +376,7 @@ var CostControl = (function() {
};
ConfigManager.setOption({ 'lastDataUsage': lastDataUsage },
function _onSetItem() {
- debug('Statistics up to date and stored');
+ debug('Statistics up to date and stored.');
}
);
// XXX: Enrich with the samples because I can not store them
@@ -397,7 +398,6 @@ var CostControl = (function() {
var output = [];
var totalData, accum = 0;
for (var i = 0, item; item = data[i]; i++) {
- debug('Tag: ' + JSON.stringify(item));
totalData = 0;
if (item.rxBytes)
totalData += item.rxBytes;
View
11 apps/costcontrol/js/message_handler.js
@@ -33,7 +33,7 @@
// https://bugzilla.mozilla.org/show_bug.cgi?id=800431
function setNextReset(when) {
asyncStorage.getItem('nextResetAlarm', function(id) {
- debug('Current nextResetAlarm ' + id + (id ? '. Removing.' : ''));
+ debug('Current nextResetAlarm', id + '.', id ? 'Removing.' : '');
if (id)
navigator.mozAlarms.remove(id);
@@ -48,7 +48,7 @@
ConfigManager.setOption({ nextReset: when }, function _sync() {
localStorage['sync'] = 'nextReset#' + Math.random();
});
- debug('Setting nextResetAlarm ' + request.result + ' to ' + when);
+ debug('Setting nextResetAlarm', request.result, 'to', when);
asyncStorage.setItem('nextResetAlarm', request.result);
};
});
@@ -113,8 +113,7 @@
// Remove the timeout
navigator.mozAlarms.remove(settings.waitingForBalance);
- debug('Balance timeout: ' + settings.waitingForBalance +
- ' removed');
+ debug('Balance timeout:', settings.waitingForBalance, 'removed');
// Store new balance and sync
ConfigManager.setOption(
@@ -129,7 +128,7 @@
} else if (isConfirmation) {
// Store SUCCESS for TopIp and sync
navigator.mozAlarms.remove(settings.waitingForTopUp);
- debug('TopUp timeout: ' + settings.waitingForTopUp + ' removed');
+ debug('TopUp timeout:', settings.waitingForTopUp, 'removed');
ConfigManager.setOption(
{ 'waitingForTopUp': null },
function _onSet() {
@@ -143,7 +142,7 @@
// Store ERROR for TopUp and sync
settings.errors['INCORRECT_TOPUP_CODE'] = true;
navigator.mozAlarms.remove(settings.waitingForTopUp);
- debug('TopUp timeout: ' + settings.waitingForTopUp + ' removed');
+ debug('TopUp timeout: ', settings.waitingForTopUp, 'removed');
ConfigManager.setOption(
{ 'errors': settings.errors, 'waitingForTopUp': null },
function _onSet() {
View
105 apps/costcontrol/js/mindgap.js
@@ -57,7 +57,7 @@
* ----------------------------
* In order to build the list of tags, the module should be informed as soon as
* the device is started to check if a SIM change was made. If so, the last tag
- * is closed and a new one open.
+ * is closed and a new one is open.
*
* Closing a tag is to compute current and offset values and set the end date.
* Opening a tag is to add a new tag object with the SIM id and the start date.
@@ -66,9 +66,9 @@
* moment of the switch.
*
* > offset value is calculated by:
- * a) if there is a fixing value -> offset = actual - fixing
- * b) if there is only one tag -> offset = actual
- * c) if there is more than one, -> offset =
+ * a) if there is a fixing value for now -> offset = actual - fixing
+ * b) if there is only one tag -> offset = actual
+ * c) if there is more than one, -> offset =
* (actual - <previous tag's current>) + <last tag with same SIM's offset>
*
* 2- Setting a fixing value
@@ -89,13 +89,21 @@
* labelling the goal date. We say a tag labels a date if:
* a) tag's start or end refer to the same day as date or
* b) date is between tag's start and tag's end or
- * c) date is latter then tag's start and there is no tag's end
+ * c) date is latter than tag's start and there is no tag's end
*
* Now passing through this subset in reverse order we look for the first tag
- * with the SIM required. Two cases can occur:
- * a) if the tag has no end or the end is not the goal date, -> usage =
- * (actual - <previous tag's current>) + <last tag with same SIM's offset>
- * b) else -> usage = tag's offset
+ * with the SIM required. Several cases can occur:
+ * a) the tag is closed -> usage = tag's offset
+ * b) the tag has no end or the end is not the goal date, -> usage =
+ *
+ * (actual - <previous tag's actual>*) + <last tag with same SIM's offset>**
+ * if there is no fixing value for the goal date
+ *
+ * actual - <fixing value for goal date>
+ * if there is a fixing value for the goal date
+ *
+ * ( *) Or 0 if there is no previous tag
+ * (**) Or 0 if there is no a closed tag
*
* Conclussions
* ============
@@ -115,7 +123,7 @@ var MindGap = (function() {
return window.parent.location.pathname === '/handle_gaps.html';
}
- // Gets the tag list and currentUsage and pass it to the callback
+ // Closes the current tag and open a new one
function updateTagList(newSIM) {
var now = new Date();
asyncStorage.getItem('dataUsageTags', function _onTags(tags) {
@@ -134,7 +142,7 @@ var MindGap = (function() {
// Now close the last tag and open new
closeLastTag(tags, currentDataUsage, now);
openNewTag(tags, newSIM, now);
- debug('After: ' + JSON.stringify(tags));
+ debug('After: ', tags);
// Finally store tags again
asyncStorage.setItem('dataUsageTags', tags, function _done() {
@@ -146,10 +154,10 @@ var MindGap = (function() {
// Adds a new tag to the taglist
function openNewTag(tags, newSIM, when) {
- tags.push({ sim: newSIM, start: when });
+ tags.push({ sim: newSIM, start: when, fixing: [] });
}
- // Adds fields end, actual and offset to current opened tag
+ // Adds fields end, actual and offset to current open tag
function closeLastTag(tags, currentDataUsage, when) {
if (!tags.length)
return;
@@ -157,23 +165,26 @@ var MindGap = (function() {
var tag = tags[tags.length - 1];
tag.actual = currentDataUsage;
- if (tag.fixing !== undefined) {
- tag.offset = tag.actual - tag.fixing;
-
- } else if (tags.length < 2) {
+ if (tags.length < 2) {
tag.offset = tag.actual;
} else {
- var sim = tag.sim;
- var previous = tags[tags.length - 2];
- tag.offset = (tag.actual - previous.actual) + getLastOffset(sim, tags);
+ var fixing = getFixingFor(when, tag.fixing);
+ if (fixing !== null) {
+ tag.offset = tag.actual - fixing;
+ } else {
+ var sim = tag.sim;
+ var previous = tags[tags.length - 2];
+ tag.offset = (tag.actual - previous.actual) +
+ getLastClosedOffset(sim, tags);
+ }
}
tag.end = when; // XXX: close at the end. Very important!
}
- // Return the offset of the last time the same SIM was in use
- function getLastOffset(referenceSIM, tags) {
+ // Return the offset of the last closed tag for the reference SIM
+ function getLastClosedOffset(referenceSIM, tags) {
for (var i = tags.length - 1; i >= 0; i--) {
var ctag = tags[i];
if (ctag.sim === referenceSIM && ctag.end !== undefined)
@@ -184,27 +195,46 @@ var MindGap = (function() {
// Return the usage for the inserted SIM for a date
function getUsage(tags, currentUsage, date) {
+ debug('Current usage:', currentUsage);
+
var tag = tags[tags.length - 1];
var sim = tag.sim;
- var todayTags = getTagsForDate(tags, date);
+ var dateTags = getTagsForDate(tags, date);
- var usage; // undefined is a valid value (means no data for that date)
- for (var i = todayTags.length - 1; i >= 0; i--) {
- var ctag = todayTags[i];
+ debug('Last tag:', tag);
+ var usage; // XXX: undefined is a valid value (means no data for that date)
+ for (var i = dateTags.length - 1; i >= 0; i--) {
+ var ctag = dateTags[i];
if (ctag.sim === tag.sim) {
+ debug('Same SIM tag:', ctag);
- // Opened tag
+ // Open tag
if (ctag.end === undefined || !sameDate(date, ctag.end)) {
- var prevUsage = tags[i - 1] === undefined ? 0 : tags[i - 1].actual;
- usage = currentUsage - prevUsage + getLastOffset(sim, todayTags);
+ debug('Open tag case.');
+
+ var fixing = getFixingFor(date, ctag.fixing);
+ if (fixing !== null) {
+ debug('Fixing with:', fixing);
+ usage = currentUsage - fixing;
+
+ } else {
+ var prevUsage = dateTags[i - 1] === undefined ? 0 :
+ dateTags[i - 1].actual;
+ var offset = getLastClosedOffset(sim, dateTags);
+ debug('Previous usage:', prevUsage);
+ debug('Last same SIM usage:', offset);
+ usage = currentUsage - prevUsage + offset;
+ }
// Closed tag
} else {
+ debug('Closed tag case. Taking offset:', ctag.offset);
usage = ctag.offset;
}
return usage;
}
}
+ debug('No tag found!');
return usage;
}
@@ -215,16 +245,16 @@ var MindGap = (function() {
// c) date is latter then tag's start and there is no tag's end
function getTagsForDate(tags, date) {
var time = date.getTime();
- var todayTags = [];
+ var dateTags = [];
for (var i = 0, len = tags.length; i < len; i++) {
var tag = tags[i];
if (sameDate(date, tag.start) || tag.end && sameDate(date, tag.end) ||
tag.start.getTime() < time && tag.end === undefined ||
tag.start.getTime() < time && time < tag.end.getTime())
- todayTags.push(tag);
+ dateTags.push(tag);
}
- return todayTags;
+ return dateTags;
}
// Return true is dateA and dateB refer to the same day
@@ -234,6 +264,17 @@ var MindGap = (function() {
dateA.getDay() === dateB.getDay();
}
+ // Return the fixing value for a date given a list of fixing pairs
+ function getFixingFor(date, fixingList) {
+ fixingList = fixingList || [];
+ for (var i = fixingList.length - 1; i >= 0; i--) {
+ var cfixing = fixingList[i];
+ if (sameDate(cfixing[0], date))
+ return cfixing[1];
+ }
+ return null;
+ }
+
return {
// Mechanism 1: build the tag list
updateTagList: updateTagList,
View
8 apps/costcontrol/js/settings/settings.js
@@ -11,7 +11,7 @@ var Settings = (function() {
'use strict';
- var costcontrol, vmanager, autosettings;
+ var costcontrol, vmanager, autosettings, initialized;
var plantypeSelector, phoneActivityTitle, phoneActivitySettings;
var balanceTitle, balanceSettings, reportsTitle;
function configureUI() {
@@ -65,6 +65,8 @@ var Settings = (function() {
ConfigManager.observe('resetTime', _updateNextReset, true);
ConfigManager.observe('trackingPeriod', _updateNextReset, true);
+ initialized = true;
+
updateUI();
});
}
@@ -110,7 +112,9 @@ var Settings = (function() {
}
window.addEventListener('localized', function _onLocalize() {
- updateUI();
+ if (initialized) {
+ updateUI();
+ }
});
var currentMode;
View
5 apps/costcontrol/js/utils/debug.js
@@ -1,4 +1,4 @@
-var debug = (function () {
+var debug = (function() {
var DEBUG_ID = 0;
var DEBUGGING = false;
@@ -20,7 +20,8 @@ var debug = (function () {
var uId = DEBUG_ID++;
var message = ['(' + uId + ')', DEBUG_PREFIX, parents];
- for (var i = 0, obj; obj = arguments[i]; i++) {
+ for (var i = 0, len = arguments.length, obj; i < len; i++) {
+ obj = arguments[i];
message.push(typeof obj === 'object' ? JSON.stringify(obj) : obj);
}
if (window.dump)
View
14 apps/costcontrol/js/views/balance.js
@@ -110,7 +110,7 @@ var BalanceTab = (function() {
// On balance update received
function onBalance(balance, old, key, settings) {
- debug('Balance received: ' + JSON.stringify(balance) + '!');
+ debug('Balance received:', balance);
setBalanceMode('default');
updateBalance(balance, settings.lowLimit && settings.lowLimitThreshold);
debug('Balance updated!');
@@ -162,7 +162,7 @@ var BalanceTab = (function() {
var code = topUpCodeInput.value.trim();
var requestObj = { type: 'topup', data: code };
costcontrol.request(requestObj, function _onTopUpRequest(result) {
- debug(JSON.stringify(result));
+ debug(result);
sendCode.disabled = false;
var status = result.status;
@@ -192,7 +192,7 @@ var BalanceTab = (function() {
// On top up timeout or incorrect code
function onTopUpErrors(errors) {
- debug('ERRORS: ' + JSON.stringify(errors));
+ debug('ERRORS:', errors);
var mode;
if (errors['TOPUP_TIMEOUT']) {
@@ -203,7 +203,7 @@ var BalanceTab = (function() {
errors['INCORRECT_TOPUP_CODE'] = false;
mode = 'incorrect_code';
}
- debug('Most important error: ' + mode);
+ debug('Most important error: ', mode);
// XXX: Very important to call this only if something has changed. If not,
// infinite events are triggered.
@@ -224,14 +224,14 @@ var BalanceTab = (function() {
var requestObj = { type: 'balance', force: !!force };
costcontrol.request(requestObj, function _onRequest(result) {
- debug(JSON.stringify(result));
+ debug(result);
updateButton.disabled = false;
var status = result.status;
var balance = result.data;
setBalanceMode(status === 'error' ? 'warning' : 'updating');
if (status === 'error')
setErrors(status.details);
- debug(JSON.stringify(settings));
+ debug(settings);
updateBalance(balance,
settings.lowLimit && settings.lowLimitThreshold);
});
@@ -345,7 +345,7 @@ var BalanceTab = (function() {
// Decide which error should be shown taking in count error priorities
function setErrors(error) {
- debug('TODO: Error for ' + error);
+ debug('TODO: Error for', error);
}
return {
View
2 apps/costcontrol/js/views/datausage.js
@@ -192,7 +192,7 @@ var DataUsageTab = (function() {
function changeLastReset(value) {
model.axis.X.lower = value ? new Date(value) : new Date(yesterday);
expandModel(model);
- updateUI();
+ requestDataUsage();
}
function changeNextReset(value, old, key, settings) {
View
4 apps/costcontrol/js/views/telephony.js
@@ -37,7 +37,7 @@ var TelephonyTab = (function() {
// Configure updates
document.addEventListener('mozvisibilitychange', updateWhenVisible, true);
ConfigManager.observe('lastTelephonyActivity', updateCounters, true);
- ConfigManager.observe('lastTelephonyReset', updateTimePeriod, true);
+ ConfigManager.observe('lastTelephonyReset', updateUI, true);
ConfigManager.observe('nextReset', updateNextReset, true);
updateUI();
@@ -56,7 +56,7 @@ var TelephonyTab = (function() {
document.removeEventListener('mozvisibilitychange', updateWhenVisible);
ConfigManager.removeObserver('lastTelephonyActivity', updateCounters);
- ConfigManager.removeObserver('lastTelephonyReset', updateTimePeriod);
+ ConfigManager.removeObserver('lastTelephonyReset', updateUI);
ConfigManager.removeObserver('nextReset', updateNextReset);
initialized = false;
View
39 apps/costcontrol/js/widget.js
@@ -14,13 +14,33 @@
var costcontrol;
window.addEventListener('DOMContentLoaded', function _onDOMReady() {
- checkSIMChange();
+ var mobileConnection = window.navigator.mozMobileConnection;
+
+ // No SIM
+ if (!mobileConnection || mobileConnection.cardState === 'absent') {
+ //TODO: Put the NO SIM message
+ return;
+
+ // SIM is not ready
+ } else if (mobileConnection.cardState !== 'ready') {
+ debug('SIM not ready:', mobileConnection.cardState);
+ mobileConnection.oniccinfochange = _onDOMReady;
+
+ // SIM is ready
+ } else {
+ debug('SIM ready. ICCID:', mobileConnection.iccInfo.iccid);
+ mobileConnection.oniccinfochange = undefined;
+ _startWidget();
+ }
+ });
+ function _startWidget() {
+ checkSIMChange();
CostControl.getInstance(function _onCostControlReady(instance) {
costcontrol = instance;
setupWidget();
});
- });
+ }
window.addEventListener('localized', function _onLocalize() {
if (initialized)
@@ -42,6 +62,8 @@
ConfigManager.observe('lastBalance', onBalance, true);
ConfigManager.observe('waitingForBalance', onErrors, true);
ConfigManager.observe('errors', onErrors, true);
+ ConfigManager.observe('lastDataReset', onReset, true);
+ ConfigManager.observe('lastTelephonyReset', onReset, true);
// Update UI when visible
document.addEventListener('mozvisibilitychange',
@@ -76,7 +98,7 @@
// On balance update received
function onBalance(balance, old, key, settings) {
- debug('Balance received: ' + JSON.stringify(balance) + '!');
+ debug('Balance received:', balance);
setBalanceMode('default');
updateBalance(balance, settings.lowLimit && settings.lowLimitThreshold);
debug('Balance updated!');
@@ -93,13 +115,18 @@
ConfigManager.setOption({errors: errors});
}
+ // On reset telephony or data usage
+ function onReset(value, old, key, settings) {
+ updateUI();
+ }
+
// USER INTERFACE
var currentMode;
function updateUI() {
ConfigManager.requestAll(function _onInfo(configuration, settings) {
var mode = costcontrol.getApplicationMode(settings);
- debug('Widget UI mode: ' + mode);
+ debug('Widget UI mode:', mode);
var isPrepaid = (mode === 'PREPAID');
var isDataUsageOnly = (mode === 'DATA_USAGE_ONLY');
@@ -194,7 +221,7 @@
requestObj = { type: 'balance' };
costcontrol.request(requestObj, function _onRequest(result) {
- debug(JSON.stringify(result));
+ debug(result);
var status = result.status;
var balance = result.data;
setBalanceMode(status === 'error' ? 'warning' : 'updating');
@@ -231,7 +258,7 @@
// Balance not available
if (balance === null) {
- debug('Balance not available');
+ debug('Balance not available.');
document.getElementById('balance-credit').innerHTML = _('not-available');
views.balance.querySelector('.meta').innerHTML = '';
return;
View
5 apps/system/js/cost_control.js
@@ -1,9 +1,10 @@
/* -*- Mode: js; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- /
/* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */
-'use strict';
-
(function() {
+
+ 'use strict';
+
var host = document.location.host;
var domain = host.replace(/(^[\w\d]+\.)?([\w\d]+\.[a-z]+)/, '$2');
var protocol = document.location.protocol + '//';

0 comments on commit b9c5d81

Please sign in to comment.
Something went wrong with that request. Please try again.