Migrate chrome storage API to window.localStorage

Add remove function

Remove callback from set and remove

Rebased

Rebased
10.8-maintenance
Mark Haslinghuis 2021-10-18 01:45:30 +02:00
parent c86348b4db
commit f41e135333
17 changed files with 597 additions and 636 deletions

View File

@ -4,7 +4,7 @@
// localStorage deals with strings, not objects, so the objects have been serialized.
const ConfigStorage = {
// key can be one string, or array of strings
get: function(key, callback) {
get: function(key) {
let result = {};
if (Array.isArray(key)) {
key.forEach(function (element) {
@ -14,7 +14,6 @@ const ConfigStorage = {
// is okay
}
});
callback?.(result);
} else {
const keyValue = window.localStorage.getItem(key);
if (keyValue) {
@ -23,9 +22,6 @@ const ConfigStorage = {
} catch (e) {
// It's fine if we fail that parse
}
callback?.(result);
} else {
callback?.(result);
}
}
@ -39,4 +35,7 @@ const ConfigStorage = {
window.localStorage.setItem(element, JSON.stringify(tmpObj));
});
},
remove: function(item) {
window.localStorage.removeItem(item);
},
};

View File

@ -44,19 +44,18 @@ let FirmwareCache = (function () {
function persist(data) {
let obj = {};
obj[CACHEKEY] = data;
chrome.storage.local.set(obj);
ConfigStorage.set(obj);
}
/**
* @param {Function} callback
*/
function load(callback) {
chrome.storage.local.get(CACHEKEY, obj => {
let entries = typeof obj === "object" && obj.hasOwnProperty(CACHEKEY)
? obj[CACHEKEY]
: [];
callback(entries);
});
const obj = ConfigStorage.get(CACHEKEY);
let entries = typeof obj === "object" && obj.hasOwnProperty(CACHEKEY)
? obj[CACHEKEY]
: [];
callback(entries);
}
return {
@ -76,18 +75,14 @@ let FirmwareCache = (function () {
}
let key = oldest[0];
let cacheKey = withCachePrefix(key);
chrome.storage.local.get(cacheKey, obj => {
/** @type {CacheItem} */
let cached = typeof obj === "object" && obj.hasOwnProperty(cacheKey)
? obj[cacheKey]
: null;
if (cached === null) {
return;
}
chrome.storage.local.remove(cacheKey, () => {
onRemoveFromCache(cached.release);
});
});
const obj = ConfigStorage.get(cacheKey);
/** @type {CacheItem} */
const cached = typeof obj === "object" && obj.hasOwnProperty(cacheKey) ? obj[cacheKey] : null;
if (cached === null) {
return undefined;
}
ConfigStorage.remove(cacheKey);
onRemoveFromCache(cached.release);
return oldest;
};
@ -143,9 +138,8 @@ let FirmwareCache = (function () {
release: release,
hexdata: hexdata,
};
chrome.storage.local.set(obj, () => {
onPutToCache(release);
});
ConfigStorage.set(obj);
onPutToCache(release);
}
/**
@ -163,13 +157,9 @@ let FirmwareCache = (function () {
return;
}
let cacheKey = withCachePrefix(key);
chrome.storage.local.get(cacheKey, obj => {
/** @type {CacheItem} */
let cached = typeof obj === "object" && obj.hasOwnProperty(cacheKey)
? obj[cacheKey]
: null;
callback(cached);
});
const obj = ConfigStorage.get(cacheKey);
const cached = typeof obj === "object" && obj.hasOwnProperty(cacheKey) ? obj[cacheKey] : null;
callback(cached);
}
/**
@ -184,19 +174,19 @@ let FirmwareCache = (function () {
for (let key of journal.keys()) {
cacheKeys.push(withCachePrefix(key));
}
chrome.storage.local.get(cacheKeys, obj => {
if (typeof obj !== "object") {
return;
const obj = ConfigStorage.get(cacheKeys);
if (typeof obj !== "object") {
return;
}
console.log(obj.entries());
for (let cacheKey of cacheKeys) {
if (obj.hasOwnProperty(cacheKey)) {
/** @type {CacheItem} */
let item = obj[cacheKey];
onRemoveFromCache(item.release);
}
for (let cacheKey of cacheKeys) {
if (obj.hasOwnProperty(cacheKey)) {
/** @type {CacheItem} */
let item = obj[cacheKey];
onRemoveFromCache(item.release);
}
}
chrome.storage.local.remove(cacheKeys);
});
}
ConfigStorage.remove(cacheKeys);
journal.clear();
JournalStorage.persist(journal.toJSON());
}

View File

@ -22,29 +22,27 @@ const cordovaUI = {
if (screenWidth > 575 && screenHeight > 575) {
self.canChangeUI = false;
}
ConfigStorage.get('cordovaForceComputerUI', function (result) {
if (result.cordovaForceComputerUI === undefined) {
if ((orientation === 'landscape' && screenHeight <= 575)
|| (orientation === 'portrait' && screenWidth <= 575)) {
ConfigStorage.set({'cordovaForceComputerUI': false});
} else {
ConfigStorage.set({'cordovaForceComputerUI': true});
}
const result = ConfigStorage.get('cordovaForceComputerUI');
if (result.cordovaForceComputerUI === undefined) {
if ((orientation === 'landscape' && screenHeight <= 575)
|| (orientation === 'portrait' && screenWidth <= 575)) {
ConfigStorage.set({'cordovaForceComputerUI': false});
} else {
ConfigStorage.set({'cordovaForceComputerUI': true});
}
});
}
self.set();
},
set: function() {
const self = this;
ConfigStorage.get('cordovaForceComputerUI', function (result) {
if (result.cordovaForceComputerUI) {
window.screen.orientation.lock('landscape');
$('body').css('zoom', self.uiZoom);
} else {
window.screen.orientation.lock('portrait');
$('body').css('zoom', 1);
}
});
const result = ConfigStorage.get('cordovaForceComputerUI');
if (result.cordovaForceComputerUI) {
window.screen.orientation.lock('landscape');
$('body').css('zoom', self.uiZoom);
} else {
window.screen.orientation.lock('portrait');
$('body').css('zoom', 1);
}
},
};

View File

@ -389,13 +389,12 @@ GuiControl.prototype.content_ready = function (callback) {
};
GuiControl.prototype.selectDefaultTabWhenConnected = function() {
ConfigStorage.get(['rememberLastTab', 'lastTab'], function (result) {
if (result.rememberLastTab && result.lastTab) {
$(`#tabs ul.mode-connected .${result.lastTab} a`).click();
} else {
$('#tabs ul.mode-connected .tab_setup a').click();
}
});
const result = ConfigStorage.get(['rememberLastTab', 'lastTab']);
if (result.rememberLastTab && result.lastTab) {
$(`#tabs ul.mode-connected .${result.lastTab} a`).click();
} else {
$('#tabs ul.mode-connected .tab_setup a').click();
}
};
GuiControl.prototype.isNWJS = function () {

View File

@ -21,45 +21,44 @@ JenkinsLoader.prototype.loadJobs = function (viewName, callback) {
callback(jobs);
};
chrome.storage.local.get([cacheLastUpdateTag, jobsDataTag], function (result) {
const jobsDataTimestamp = $.now();
const cachedJobsData = result[jobsDataTag];
const cachedJobsLastUpdate = result[cacheLastUpdateTag];
const result = ConfigStorage.get([cacheLastUpdateTag, jobsDataTag]);
const jobsDataTimestamp = $.now();
const cachedJobsData = result[jobsDataTag];
const cachedJobsLastUpdate = result[cacheLastUpdateTag];
const cachedCallback = () => {
if (cachedJobsData) {
GUI.log(i18n.getMessage('buildServerUsingCached', ['jobs']));
}
wrappedCallback(cachedJobsData ? cachedJobsData : []);
};
if (!cachedJobsData || !cachedJobsLastUpdate || jobsDataTimestamp - cachedJobsLastUpdate > self._cacheExpirationPeriod) {
const url = `${viewUrl}${self._jobsRequest}`;
$.get(url, jobsInfo => {
GUI.log(i18n.getMessage('buildServerLoaded', ['jobs']));
// remove Betaflight prefix, rename Betaflight job to Development
const jobs = jobsInfo.jobs.map(job => {
return { title: job.name.replace('Betaflight ', '').replace('Betaflight', 'Development'), name: job.name };
});
// cache loaded info
const object = {};
object[jobsDataTag] = jobs;
object[cacheLastUpdateTag] = $.now();
chrome.storage.local.set(object);
wrappedCallback(jobs);
}).fail(xhr => {
GUI.log(i18n.getMessage('buildServerLoadFailed', ['jobs', `HTTP ${xhr.status}`]));
cachedCallback();
});
} else {
cachedCallback();
const cachedCallback = () => {
if (cachedJobsData) {
GUI.log(i18n.getMessage('buildServerUsingCached', ['jobs']));
}
});
wrappedCallback(cachedJobsData ? cachedJobsData : []);
};
if (!cachedJobsData || !cachedJobsLastUpdate || jobsDataTimestamp - cachedJobsLastUpdate > self._cacheExpirationPeriod) {
const url = `${viewUrl}${self._jobsRequest}`;
$.get(url, jobsInfo => {
GUI.log(i18n.getMessage('buildServerLoaded', ['jobs']));
// remove Betaflight prefix, rename Betaflight job to Development
const jobs = jobsInfo.jobs.map(job => {
return { title: job.name.replace('Betaflight ', '').replace('Betaflight', 'Development'), name: job.name };
});
// cache loaded info
const object = {};
object[jobsDataTag] = jobs;
object[cacheLastUpdateTag] = $.now();
ConfigStorage.set(object);
wrappedCallback(jobs);
}).fail(xhr => {
GUI.log(i18n.getMessage('buildServerLoadFailed', ['jobs', `HTTP ${xhr.status}`]));
cachedCallback();
});
} else {
cachedCallback();
}
};
JenkinsLoader.prototype.loadBuilds = function (jobName, callback) {
@ -69,49 +68,48 @@ JenkinsLoader.prototype.loadBuilds = function (jobName, callback) {
const buildsDataTag = `${jobUrl}BuildsData`;
const cacheLastUpdateTag = `${jobUrl}BuildsLastUpdate`;
chrome.storage.local.get([cacheLastUpdateTag, buildsDataTag], function (result) {
const buildsDataTimestamp = $.now();
const cachedBuildsData = result[buildsDataTag];
const cachedBuildsLastUpdate = result[cacheLastUpdateTag];
const result = ConfigStorage.get([cacheLastUpdateTag, buildsDataTag]);
const buildsDataTimestamp = $.now();
const cachedBuildsData = result[buildsDataTag];
const cachedBuildsLastUpdate = result[cacheLastUpdateTag];
const cachedCallback = () => {
if (cachedBuildsData) {
GUI.log(i18n.getMessage('buildServerUsingCached', [jobName]));
}
self._parseBuilds(jobUrl, jobName, cachedBuildsData ? cachedBuildsData : [], callback);
};
if (!cachedBuildsData || !cachedBuildsLastUpdate || buildsDataTimestamp - cachedBuildsLastUpdate > self._cacheExpirationPeriod) {
const url = `${jobUrl}${self._buildsRequest}`;
$.get(url, function (buildsInfo) {
GUI.log(i18n.getMessage('buildServerLoaded', [jobName]));
// filter successful builds
const builds = buildsInfo.builds.filter(build => build.result == 'SUCCESS')
.map(build => ({
number: build.number,
artifacts: build.artifacts.map(artifact => artifact.relativePath),
changes: build.changeSet.items.map(item => `* ${item.msg}`).join('<br>\n'),
timestamp: build.timestamp,
}));
// cache loaded info
const object = {};
object[buildsDataTag] = builds;
object[cacheLastUpdateTag] = $.now();
chrome.storage.local.set(object);
self._parseBuilds(jobUrl, jobName, builds, callback);
}).fail(xhr => {
GUI.log(i18n.getMessage('buildServerLoadFailed', [jobName, `HTTP ${xhr.status}`]));
cachedCallback();
});
} else {
cachedCallback();
const cachedCallback = () => {
if (cachedBuildsData) {
GUI.log(i18n.getMessage('buildServerUsingCached', [jobName]));
}
});
self._parseBuilds(jobUrl, jobName, cachedBuildsData ? cachedBuildsData : [], callback);
};
if (!cachedBuildsData || !cachedBuildsLastUpdate || buildsDataTimestamp - cachedBuildsLastUpdate > self._cacheExpirationPeriod) {
const url = `${jobUrl}${self._buildsRequest}`;
$.get(url, function (buildsInfo) {
GUI.log(i18n.getMessage('buildServerLoaded', [jobName]));
// filter successful builds
const builds = buildsInfo.builds.filter(build => build.result == 'SUCCESS')
.map(build => ({
number: build.number,
artifacts: build.artifacts.map(artifact => artifact.relativePath),
changes: build.changeSet.items.map(item => `* ${item.msg}`).join('<br>\n'),
timestamp: build.timestamp,
}));
// cache loaded info
const object = {};
object[buildsDataTag] = builds;
object[cacheLastUpdateTag] = $.now();
ConfigStorage.set(object);
self._parseBuilds(jobUrl, jobName, builds, callback);
}).fail(xhr => {
GUI.log(i18n.getMessage('buildServerLoadFailed', [jobName, `HTTP ${xhr.status}`]));
cachedCallback();
});
} else {
cachedCallback();
}
};
JenkinsLoader.prototype._parseBuilds = function (jobUrl, jobName, builds, callback) {

View File

@ -190,22 +190,16 @@ i18n.localizePage = function(forceReTranslate) {
* returns the current locale to the callback
*/
function getStoredUserLocale(cb) {
let userLanguage = 'DEFAULT';
if (typeof ConfigStorage !== 'undefined') {
ConfigStorage.get('userLanguageSelect', function (result) {
let userLanguage = 'DEFAULT';
if (result.userLanguageSelect) {
userLanguage = result.userLanguageSelect;
}
i18n.selectedLanguage = userLanguage;
userLanguage = getValidLocale(userLanguage);
cb(userLanguage);
});
} else {
const userLanguage = getValidLocale('DEFAULT');
cb(userLanguage);
const result = ConfigStorage.get('userLanguageSelect');
if (result.userLanguageSelect) {
userLanguage = result.userLanguageSelect;
}
i18n.selectedLanguage = userLanguage;
}
userLanguage = getValidLocale(userLanguage);
cb(userLanguage);
}
function getValidLocale(userLocale) {

View File

@ -45,13 +45,12 @@ function appReady() {
function checkSetupAnalytics(callback) {
if (!analytics) {
setTimeout(function () {
ConfigStorage.get(['userId', 'analyticsOptOut', 'checkForConfiguratorUnstableVersions' ], function (result) {
if (!analytics) {
setupAnalytics(result);
}
const result = ConfigStorage.get(['userId', 'analyticsOptOut', 'checkForConfiguratorUnstableVersions' ]);
if (!analytics) {
setupAnalytics(result);
}
callback(analytics);
});
callback(analytics);
});
} else if (callback) {
callback(analytics);
@ -499,48 +498,45 @@ function startProcess() {
$(this).data('state', state);
});
ConfigStorage.get('logopen', function (result) {
if (result.logopen) {
$("#showlog").trigger('click');
}
});
let result = ConfigStorage.get('logopen');
if (result.logopen) {
$("#showlog").trigger('click');
}
ConfigStorage.get('permanentExpertMode', function (result) {
const expertModeCheckbox = 'input[name="expertModeCheckbox"]';
if (result.permanentExpertMode) {
$(expertModeCheckbox).prop('checked', true);
}
result = ConfigStorage.get('permanentExpertMode');
const expertModeCheckbox = 'input[name="expertModeCheckbox"]';
if (result.permanentExpertMode) {
$(expertModeCheckbox).prop('checked', true);
}
$(expertModeCheckbox).on("change", () => {
const checked = $(expertModeCheckbox).is(':checked');
checkSetupAnalytics(function (analyticsService) {
analyticsService.setDimension(analyticsService.DIMENSIONS.CONFIGURATOR_EXPERT_MODE, checked ? 'On' : 'Off');
});
if (FC.FEATURE_CONFIG && FC.FEATURE_CONFIG.features !== 0) {
updateTabList(FC.FEATURE_CONFIG.features);
}
if (GUI.active_tab) {
TABS[GUI.active_tab]?.expertModeChanged?.(checked);
}
$(expertModeCheckbox).on("change", () => {
const checked = $(expertModeCheckbox).is(':checked');
checkSetupAnalytics(function (analyticsService) {
analyticsService.setDimension(analyticsService.DIMENSIONS.CONFIGURATOR_EXPERT_MODE, checked ? 'On' : 'Off');
});
$(expertModeCheckbox).trigger("change");
});
if (FC.FEATURE_CONFIG && FC.FEATURE_CONFIG.features !== 0) {
updateTabList(FC.FEATURE_CONFIG.features);
}
ConfigStorage.get('cliAutoComplete', function (result) {
CliAutoComplete.setEnabled(typeof result.cliAutoComplete == 'undefined' || result.cliAutoComplete); // On by default
});
ConfigStorage.get('darkTheme', function (result) {
if (result.darkTheme === undefined || typeof result.darkTheme !== "number") {
// sets dark theme to auto if not manually changed
setDarkTheme(2);
} else {
setDarkTheme(result.darkTheme);
if (GUI.active_tab) {
TABS[GUI.active_tab]?.expertModeChanged?.(checked);
}
});
$(expertModeCheckbox).trigger("change");
result = ConfigStorage.get('cliAutoComplete');
CliAutoComplete.setEnabled(typeof result.cliAutoComplete === undefined || result.cliAutoComplete); // On by default
result = ConfigStorage.get('darkTheme');
if (result.darkTheme === undefined || typeof result.darkTheme !== "number") {
// sets dark theme to auto if not manually changed
setDarkTheme(2);
} else {
setDarkTheme(result.darkTheme);
}
if (GUI.isCordova()) {
let darkMode = false;
const checkDarkMode = function() {
@ -575,52 +571,51 @@ function checkForConfiguratorUpdates() {
}
function notifyOutdatedVersion(releaseData) {
ConfigStorage.get('checkForConfiguratorUnstableVersions', function (result) {
let showUnstableReleases = false;
if (result.checkForConfiguratorUnstableVersions) {
showUnstableReleases = true;
const result = ConfigStorage.get('checkForConfiguratorUnstableVersions');
let showUnstableReleases = false;
if (result.checkForConfiguratorUnstableVersions) {
showUnstableReleases = true;
}
const versions = releaseData.filter(function (version) {
const semVerVersion = semver.parse(version.tag_name);
if (semVerVersion && (showUnstableReleases || semVerVersion.prerelease.length === 0)) {
return version;
} else {
return null;
}
const versions = releaseData.filter(function (version) {
const semVerVersion = semver.parse(version.tag_name);
if (semVerVersion && (showUnstableReleases || semVerVersion.prerelease.length === 0)) {
return version;
} else {
return null;
}
}).sort(function (v1, v2) {
try {
return semver.compare(v2.tag_name, v1.tag_name);
} catch (e) {
return false;
}
});
if (versions.length > 0) {
CONFIGURATOR.latestVersion = versions[0].tag_name;
CONFIGURATOR.latestVersionReleaseUrl = versions[0].html_url;
}
if (semver.lt(CONFIGURATOR.version, CONFIGURATOR.latestVersion)) {
const message = i18n.getMessage('configuratorUpdateNotice', [CONFIGURATOR.latestVersion, CONFIGURATOR.latestVersionReleaseUrl]);
GUI.log(message);
const dialog = $('.dialogConfiguratorUpdate')[0];
$('.dialogConfiguratorUpdate-content').html(message);
$('.dialogConfiguratorUpdate-closebtn').click(function() {
dialog.close();
});
$('.dialogConfiguratorUpdate-websitebtn').click(function() {
dialog.close();
window.open(CONFIGURATOR.latestVersionReleaseUrl, '_blank');
});
dialog.showModal();
}).sort(function (v1, v2) {
try {
return semver.compare(v2.tag_name, v1.tag_name);
} catch (e) {
return false;
}
});
if (versions.length > 0) {
CONFIGURATOR.latestVersion = versions[0].tag_name;
CONFIGURATOR.latestVersionReleaseUrl = versions[0].html_url;
}
if (semver.lt(CONFIGURATOR.version, CONFIGURATOR.latestVersion)) {
const message = i18n.getMessage('configuratorUpdateNotice', [CONFIGURATOR.latestVersion, CONFIGURATOR.latestVersionReleaseUrl]);
GUI.log(message);
const dialog = $('.dialogConfiguratorUpdate')[0];
$('.dialogConfiguratorUpdate-content').html(message);
$('.dialogConfiguratorUpdate-closebtn').click(function() {
dialog.close();
});
$('.dialogConfiguratorUpdate-websitebtn').click(function() {
dialog.close();
window.open(CONFIGURATOR.latestVersionReleaseUrl, '_blank');
});
dialog.showModal();
}
}
function isExpertModeEnabled() {

View File

@ -32,9 +32,12 @@ PortHandler.initialize = function () {
PortHandler.check = function () {
const self = this;
let result;
ConfigStorage.get('showVirtualMode', res => self.showVirtualMode = res.showVirtualMode);
ConfigStorage.get('showAllSerialDevices', res => self.showAllSerialDevices = res.showAllSerialDevices);
result = ConfigStorage.get('showVirtualMode');
self.showVirtualMode = result.showVirtualMode;
result = ConfigStorage.get('showAllSerialDevices');
self.showAllSerialDevices = result.showAllSerialDevices;
self.check_usb_devices();
self.check_serial_devices();
@ -168,17 +171,16 @@ PortHandler.detectPort = function(currentPorts) {
currentPorts = self.updatePortSelect(currentPorts);
console.log(`PortHandler - Found: ${JSON.stringify(newPorts)}`);
ConfigStorage.get('last_used_port', function (result) {
if (result.last_used_port) {
if (result.last_used_port.includes('tcp')) {
self.portPickerElement.val('manual');
} else if (newPorts.length === 1) {
self.portPickerElement.val(newPorts[0].path);
} else if (newPorts.length > 1) {
self.selectPort(currentPorts);
}
const result = ConfigStorage.get('last_used_port');
if (result.last_used_port) {
if (result.last_used_port.includes('tcp')) {
self.portPickerElement.val('manual');
} else if (newPorts.length === 1) {
self.portPickerElement.val(newPorts[0].path);
} else if (newPorts.length > 1) {
self.selectPort(currentPorts);
}
});
}
self.port_available = true;
// Signal board verification

View File

@ -11,37 +11,37 @@ const ReleaseChecker = function (releaseName, releaseUrl) {
ReleaseChecker.prototype.loadReleaseData = function (processFunction) {
const self = this;
chrome.storage.local.get([self._releaseLastUpdateTag, self._releaseDataTag], function (result) {
const releaseDataTimestamp = $.now();
const cacheReleaseData = result[self._releaseDataTag];
const cachedReleaseLastUpdate = result[self._releaseLastUpdateTag];
if (!cacheReleaseData || !cachedReleaseLastUpdate || releaseDataTimestamp - cachedReleaseLastUpdate > 3600 * 1000) {
$.get(self._releaseUrl, function (releaseData) {
GUI.log(i18n.getMessage('releaseCheckLoaded',[self._releaseName]));
const result = ConfigStorage.get([self._releaseLastUpdateTag, self._releaseDataTag]);
const releaseDataTimestamp = $.now();
const cacheReleaseData = result[self._releaseDataTag];
const cachedReleaseLastUpdate = result[self._releaseLastUpdateTag];
const data = {};
data[self._releaseDataTag] = releaseData;
data[self._releaseLastUpdateTag] = releaseDataTimestamp;
chrome.storage.local.set(data, function () {});
if (!cacheReleaseData || !cachedReleaseLastUpdate || releaseDataTimestamp - cachedReleaseLastUpdate > 3600 * 1000) {
$.get(self._releaseUrl, function (releaseData) {
GUI.log(i18n.getMessage('releaseCheckLoaded',[self._releaseName]));
self._processReleaseData(releaseData, processFunction);
}).fail(function (data) {
let message = '';
if (data['responseJSON']) {
message = data['responseJSON'].message;
}
GUI.log(i18n.getMessage('releaseCheckFailed',[self._releaseName,message]));
const data = {};
data[self._releaseDataTag] = releaseData;
data[self._releaseLastUpdateTag] = releaseDataTimestamp;
ConfigStorage.set(data);
self._processReleaseData(cacheReleaseData, processFunction);
});
} else {
if (cacheReleaseData) {
GUI.log(i18n.getMessage('releaseCheckCached',[self._releaseName]));
self._processReleaseData(releaseData, processFunction);
}).fail(function (data) {
let message = '';
if (data['responseJSON']) {
message = data['responseJSON'].message;
}
GUI.log(i18n.getMessage('releaseCheckFailed',[self._releaseName,message]));
self._processReleaseData(cacheReleaseData, processFunction);
});
} else {
if (cacheReleaseData) {
GUI.log(i18n.getMessage('releaseCheckCached',[self._releaseName]));
}
});
self._processReleaseData(cacheReleaseData, processFunction);
}
};

View File

@ -33,16 +33,17 @@ function initializeSerialBackend() {
ConfigStorage.set({'portOverride': $('#port-override').val()});
});
ConfigStorage.get('portOverride', function (data) {
const data = ConfigStorage.get('portOverride');
if (data.portOverride) {
$('#port-override').val(data.portOverride);
});
}
$('div#port-picker #port').change(function (target) {
GUI.updateManualPortVisibility();
});
$('div.connect_controls a.connect').click(function () {
if (GUI.connect_lock != true) { // GUI control overrides the user control
if (!GUI.connect_lock) { // GUI control overrides the user control
const toggleStatus = function() {
clicks = !clicks;
@ -113,40 +114,39 @@ function initializeSerialBackend() {
});
// auto-connect
ConfigStorage.get('auto_connect', function (result) {
if (result.auto_connect === undefined || result.auto_connect) {
// default or enabled by user
GUI.auto_connect = true;
const result = ConfigStorage.get('auto_connect');
if (result.auto_connect === undefined || result.auto_connect) {
// default or enabled by user
GUI.auto_connect = true;
$('input.auto_connect').prop('checked', true);
$('input.auto_connect').prop('checked', true);
$('input.auto_connect, span.auto_connect').prop('title', i18n.getMessage('autoConnectEnabled'));
$('select#baud').val(115200).prop('disabled', true);
} else {
// disabled by user
GUI.auto_connect = false;
$('input.auto_connect').prop('checked', false);
$('input.auto_connect, span.auto_connect').prop('title', i18n.getMessage('autoConnectDisabled'));
}
// bind UI hook to auto-connect checkbos
$('input.auto_connect').change(function () {
GUI.auto_connect = $(this).is(':checked');
// update title/tooltip
if (GUI.auto_connect) {
$('input.auto_connect, span.auto_connect').prop('title', i18n.getMessage('autoConnectEnabled'));
$('select#baud').val(115200).prop('disabled', true);
} else {
// disabled by user
GUI.auto_connect = false;
$('input.auto_connect').prop('checked', false);
$('input.auto_connect, span.auto_connect').prop('title', i18n.getMessage('autoConnectDisabled'));
if (!GUI.connected_to && !GUI.connecting_to) $('select#baud').prop('disabled', false);
}
// bind UI hook to auto-connect checkbox
$('input.auto_connect').change(function () {
GUI.auto_connect = $(this).is(':checked');
// update title/tooltip
if (GUI.auto_connect) {
$('input.auto_connect, span.auto_connect').prop('title', i18n.getMessage('autoConnectEnabled'));
$('select#baud').val(115200).prop('disabled', true);
} else {
$('input.auto_connect, span.auto_connect').prop('title', i18n.getMessage('autoConnectDisabled'));
if (!GUI.connected_to && !GUI.connecting_to) $('select#baud').prop('disabled', false);
}
ConfigStorage.set({'auto_connect': GUI.auto_connect});
});
ConfigStorage.set({'auto_connect': GUI.auto_connect});
});
PortHandler.initialize();

View File

@ -540,16 +540,15 @@ TABS.auxiliary.initialize = function (callback) {
}
let hideUnusedModes = false;
ConfigStorage.get('hideUnusedModes', function (result) {
$("input#switch-toggle-unused")
.change(function() {
hideUnusedModes = $(this).prop("checked");
ConfigStorage.set({ hideUnusedModes: hideUnusedModes });
update_ui();
})
.prop("checked", !!result.hideUnusedModes)
.change();
});
const result = ConfigStorage.get('hideUnusedModes');
$("input#switch-toggle-unused")
.change(function() {
hideUnusedModes = $(this).prop("checked");
ConfigStorage.set({ hideUnusedModes: hideUnusedModes });
update_ui();
})
.prop("checked", !!result.hideUnusedModes)
.change();
// update ui instantly on first load
update_ui();

View File

@ -158,12 +158,11 @@ firmware_flasher.initialize = function (callback) {
TABS.firmware_flasher.releases = builds;
ConfigStorage.get('selected_board', function (result) {
if (result.selected_board) {
const boardBuilds = builds[result.selected_board];
$('select[name="board"]').val(boardBuilds ? result.selected_board : 0).trigger('change');
}
});
result = ConfigStorage.get('selected_board');
if (result.selected_board) {
const boardBuilds = builds[result.selected_board];
$('select[name="board"]').val(boardBuilds ? result.selected_board : 0).trigger('change');
}
}
function processBoardOptions(releaseData, showDevReleases) {
@ -244,30 +243,29 @@ firmware_flasher.initialize = function (callback) {
if (builds && hasUnifiedTargetBuild(builds)) {
console.log('loaded some builds for later');
const storageTag = 'unifiedSourceCache';
chrome.storage.local.get(storageTag, function (result) {
let storageObj = result[storageTag];
if (!storageObj || !storageObj.lastUpdate || checkTime - storageObj.lastUpdate > expirationPeriod) {
console.log('go get', unifiedSource);
$.get(unifiedSource, function(data, textStatus, jqXHR) {
// Cache the information for later use.
let newStorageObj = {};
let newDataObj = {};
newDataObj.lastUpdate = checkTime;
newDataObj.data = data;
newStorageObj[storageTag] = newDataObj;
chrome.storage.local.set(newStorageObj);
result = ConfigStorage.get(storageTag);
let storageObj = result[storageTag];
if (!storageObj || !storageObj.lastUpdate || checkTime - storageObj.lastUpdate > expirationPeriod) {
console.log('go get', unifiedSource);
$.get(unifiedSource, function(data, textStatus, jqXHR) {
// Cache the information for later use.
let newStorageObj = {};
let newDataObj = {};
newDataObj.lastUpdate = checkTime;
newDataObj.data = data;
newStorageObj[storageTag] = newDataObj;
ConfigStorage.set(newStorageObj);
parseUnifiedBuilds(data, builds);
}).fail(xhr => {
console.log('failed to get new', unifiedSource, 'cached data', Math.floor((checkTime - storageObj.lastUpdate) / 60), 'mins old');
parseUnifiedBuilds(storageObj.data, builds);
});
} else {
// In the event that the cache is okay
console.log('unified config cached data', Math.floor((checkTime - storageObj.lastUpdate)/60), 'mins old');
parseUnifiedBuilds(storageObj.data, builds);
}
});
parseUnifiedBuilds(data, builds);
}).fail(xhr => {
console.log('failed to get new', unifiedSource, 'cached data', Math.floor((checkTime - storageObj.lastUpdate) / 60), 'mins old');
parseUnifiedBuilds(storageObj.data, builds);
});
} else {
// In the event that the cache is okay
console.log('unified config cached data', Math.floor((checkTime - storageObj.lastUpdate)/60), 'mins old');
parseUnifiedBuilds(storageObj.data, builds);
}
} else {
populateBoardOptions(builds);
}
@ -314,13 +312,12 @@ firmware_flasher.initialize = function (callback) {
TABS.firmware_flasher.releases = releases;
TABS.firmware_flasher.unifiedConfigs = unifiedConfigs;
ConfigStorage.get('selected_board', function (result) {
if (result.selected_board) {
const boardReleases = TABS.firmware_flasher.unifiedConfigs[result.selected_board]
|| TABS.firmware_flasher.releases[result.selected_board];
$('select[name="board"]').val(boardReleases ? result.selected_board : 0).trigger('change');
}
});
result = ConfigStorage.get('selected_board');
if (result.selected_board) {
const boardReleases = TABS.firmware_flasher.unifiedConfigs[result.selected_board]
|| TABS.firmware_flasher.releases[result.selected_board];
$('select[name="board"]').val(boardReleases ? result.selected_board : 0).trigger('change');
}
}
const buildTypes = [
@ -416,7 +413,7 @@ firmware_flasher.initialize = function (callback) {
buildTypesToShow[build_type].loader();
}
chrome.storage.local.set({'selected_build_type': build_type});
ConfigStorage.set({'selected_build_type': build_type});
});
function populateBuilds(builds, target, manufacturerId, duplicateName, targetVersions, callback) {
@ -613,78 +610,77 @@ firmware_flasher.initialize = function (callback) {
const storageTag = 'unifiedConfigLast';
const expirationPeriod = 3600; // One of your earth hours.
const checkTime = Math.floor(Date.now() / 1000); // Lets deal in seconds.
chrome.storage.local.get(storageTag, function (result) {
let storageObj = result[storageTag];
const unifiedConfigList = TABS.firmware_flasher.unifiedConfigs[target];
const manufacturerIds = Object.keys(unifiedConfigList);
const duplicateName = manufacturerIds.length > 1;
result = ConfigStorage.get(storageTag);
let storageObj = result[storageTag];
const unifiedConfigList = TABS.firmware_flasher.unifiedConfigs[target];
const manufacturerIds = Object.keys(unifiedConfigList);
const duplicateName = manufacturerIds.length > 1;
const processManufacturer = function(index) {
const processNext = function () {
if (index < manufacturerIds.length - 1) {
processManufacturer(index + 1);
} else {
finishPopulatingBuilds();
}
};
const manufacturerId = manufacturerIds[index];
const targetId = `${target}+${manufacturerId}`;
// Check to see if the cached configuration is the one we want.
if (!storageObj || !storageObj.targetId || storageObj.targetId !== targetId
|| !storageObj.lastUpdate || checkTime - storageObj.lastUpdate > expirationPeriod
|| !storageObj.unifiedTarget) {
const unifiedConfig = unifiedConfigList[manufacturerId];
// Have to go and try and get the unified config, and then do stuff
$.get(unifiedConfig.download_url, function(targetConfig) {
console.log('got unified config');
let config = cleanUnifiedConfigFile(targetConfig);
if (config !== null) {
const bareBoard = grabBuildNameFromConfig(config);
TABS.firmware_flasher.bareBoard = bareBoard;
self.gitHubApi.getFileLastCommitInfo('betaflight/unified-targets', 'master', unifiedConfig.path, function (commitInfo) {
config = self.injectTargetInfo(config, target, manufacturerId, commitInfo);
setUnifiedConfig(target, bareBoard, config, manufacturerId, unifiedConfig.name, unifiedConfig.download_url, commitInfo.date);
// cache it for later
let newStorageObj = {};
newStorageObj[storageTag] = {
unifiedTarget: self.unifiedTarget,
targetId: targetId,
lastUpdate: checkTime,
};
chrome.storage.local.set(newStorageObj);
populateBuilds(builds, target, manufacturerId, duplicateName, TABS.firmware_flasher.releases[bareBoard], processNext);
});
} else {
failLoading(unifiedConfig.download_url);
}
}).fail(xhr => {
failLoading(unifiedConfig.download_url);
});
const processManufacturer = function(index) {
const processNext = function () {
if (index < manufacturerIds.length - 1) {
processManufacturer(index + 1);
} else {
console.log('We have the config cached for', targetId);
const unifiedTarget = storageObj.unifiedTarget;
const bareBoard = grabBuildNameFromConfig(unifiedTarget.config);
TABS.firmware_flasher.bareBoard = bareBoard;
if (target === bareBoard) {
self.unifiedTarget = {};
} else {
self.unifiedTarget = unifiedTarget;
}
populateBuilds(builds, target, manufacturerId, duplicateName, TABS.firmware_flasher.releases[bareBoard], processNext);
finishPopulatingBuilds();
}
};
processManufacturer(0);
});
const manufacturerId = manufacturerIds[index];
const targetId = `${target}+${manufacturerId}`;
// Check to see if the cached configuration is the one we want.
if (!storageObj || !storageObj.targetId || storageObj.targetId !== targetId
|| !storageObj.lastUpdate || checkTime - storageObj.lastUpdate > expirationPeriod
|| !storageObj.unifiedTarget) {
const unifiedConfig = unifiedConfigList[manufacturerId];
// Have to go and try and get the unified config, and then do stuff
$.get(unifiedConfig.download_url, function(targetConfig) {
console.log('got unified config');
let config = cleanUnifiedConfigFile(targetConfig);
if (config !== null) {
const bareBoard = grabBuildNameFromConfig(config);
TABS.firmware_flasher.bareBoard = bareBoard;
self.gitHubApi.getFileLastCommitInfo('betaflight/unified-targets', 'master', unifiedConfig.path, function (commitInfo) {
config = self.injectTargetInfo(config, target, manufacturerId, commitInfo);
setUnifiedConfig(target, bareBoard, config, manufacturerId, unifiedConfig.name, unifiedConfig.download_url, commitInfo.date);
// cache it for later
let newStorageObj = {};
newStorageObj[storageTag] = {
unifiedTarget: self.unifiedTarget,
targetId: targetId,
lastUpdate: checkTime,
};
ConfigStorage.set(newStorageObj);
populateBuilds(builds, target, manufacturerId, duplicateName, TABS.firmware_flasher.releases[bareBoard], processNext);
});
} else {
failLoading(unifiedConfig.download_url);
}
}).fail(xhr => {
failLoading(unifiedConfig.download_url);
});
} else {
console.log('We have the config cached for', targetId);
const unifiedTarget = storageObj.unifiedTarget;
const bareBoard = grabBuildNameFromConfig(unifiedTarget.config);
TABS.firmware_flasher.bareBoard = bareBoard;
if (target === bareBoard) {
self.unifiedTarget = {};
} else {
self.unifiedTarget = unifiedTarget;
}
populateBuilds(builds, target, manufacturerId, duplicateName, TABS.firmware_flasher.releases[bareBoard], processNext);
}
};
processManufacturer(0);
} else {
self.unifiedTarget = {};
finishPopulatingBuilds();
@ -894,85 +890,78 @@ firmware_flasher.initialize = function (callback) {
document.querySelector('select[name="board"]').addEventListener('change', updateDetectBoardButton);
document.querySelector('select[name="firmware_version"]').addEventListener('change', updateDetectBoardButton);
ConfigStorage.get('erase_chip', function (result) {
if (result.erase_chip) {
$('input.erase_chip').prop('checked', true);
} else {
$('input.erase_chip').prop('checked', false);
}
let result = ConfigStorage.get('erase_chip');
if (result.erase_chip) {
$('input.erase_chip').prop('checked', true);
} else {
$('input.erase_chip').prop('checked', false);
}
$('input.erase_chip').change(function () {
ConfigStorage.set({'erase_chip': $(this).is(':checked')});
}).change();
});
$('input.erase_chip').change(function () {
ConfigStorage.set({'erase_chip': $(this).is(':checked')});
}).change();
chrome.storage.local.get('show_development_releases', function (result) {
$('input.show_development_releases')
.prop('checked', result.show_development_releases)
.change(function () {
chrome.storage.local.set({'show_development_releases': $(this).is(':checked')});
}).change();
result = ConfigStorage.get('show_development_releases');
$('input.show_development_releases')
.prop('checked', result.show_development_releases)
.change(function () {
ConfigStorage.set({'show_development_releases': $(this).is(':checked')});
}).change();
});
result = ConfigStorage.get('selected_build_type');
// ensure default build type is selected
buildType_e.val(result.selected_build_type || 0).trigger('change');
chrome.storage.local.get('selected_build_type', function (result) {
// ensure default build type is selected
buildType_e.val(result.selected_build_type || 0).trigger('change');
});
result = ConfigStorage.get('no_reboot_sequence');
if (result.no_reboot_sequence) {
$('input.updating').prop('checked', true);
$('.flash_on_connect_wrapper').show();
} else {
$('input.updating').prop('checked', false);
}
ConfigStorage.get('no_reboot_sequence', function (result) {
if (result.no_reboot_sequence) {
$('input.updating').prop('checked', true);
// bind UI hook so the status is saved on change
$('input.updating').change(function() {
const status = $(this).is(':checked');
if (status) {
$('.flash_on_connect_wrapper').show();
} else {
$('input.updating').prop('checked', false);
$('input.flash_on_connect').prop('checked', false).change();
$('.flash_on_connect_wrapper').hide();
}
// bind UI hook so the status is saved on change
$('input.updating').change(function() {
const status = $(this).is(':checked');
if (status) {
$('.flash_on_connect_wrapper').show();
} else {
$('input.flash_on_connect').prop('checked', false).change();
$('.flash_on_connect_wrapper').hide();
}
ConfigStorage.set({'no_reboot_sequence': status});
});
$('input.updating').change();
ConfigStorage.set({'no_reboot_sequence': status});
});
ConfigStorage.get('flash_manual_baud', function (result) {
if (result.flash_manual_baud) {
$('input.flash_manual_baud').prop('checked', true);
} else {
$('input.flash_manual_baud').prop('checked', false);
}
$('input.updating').change();
// bind UI hook so the status is saved on change
$('input.flash_manual_baud').change(function() {
const status = $(this).is(':checked');
ConfigStorage.set({'flash_manual_baud': status});
});
result = ConfigStorage.get('flash_manual_baud');
if (result.flash_manual_baud) {
$('input.flash_manual_baud').prop('checked', true);
} else {
$('input.flash_manual_baud').prop('checked', false);
}
$('input.flash_manual_baud').change();
// bind UI hook so the status is saved on change
$('input.flash_manual_baud').change(function() {
const status = $(this).is(':checked');
ConfigStorage.set({'flash_manual_baud': status});
});
ConfigStorage.get('flash_manual_baud_rate', function (result) {
$('#flash_manual_baud_rate').val(result.flash_manual_baud_rate);
$('input.flash_manual_baud').change();
// bind UI hook so the status is saved on change
$('#flash_manual_baud_rate').change(function() {
const baud = parseInt($('#flash_manual_baud_rate').val());
ConfigStorage.set({'flash_manual_baud_rate': baud});
});
result = ConfigStorage.get('flash_manual_baud_rate');
$('#flash_manual_baud_rate').val(result.flash_manual_baud_rate);
$('input.flash_manual_baud_rate').change();
// bind UI hook so the status is saved on change
$('#flash_manual_baud_rate').change(function() {
const baud = parseInt($('#flash_manual_baud_rate').val());
ConfigStorage.set({'flash_manual_baud_rate': baud});
});
$('input.flash_manual_baud_rate').change();
// UI Hooks
$('a.load_file').click(function () {
self.enableFlashing(false);
@ -1175,17 +1164,16 @@ firmware_flasher.initialize = function (callback) {
function setAcknowledgementTimestamp() {
const storageObj = {};
storageObj[storageTag] = Date.now();
chrome.storage.local.set(storageObj);
ConfigStorage.set(storageObj);
}
chrome.storage.local.get(storageTag, function (result) {
if (!result[storageTag] || Date.now() - result[storageTag] > DAY_MS) {
result = ConfigStorage.get(storageTag);
if (!result[storageTag] || Date.now() - result[storageTag] > DAY_MS) {
showAcknowledgementDialog(setAcknowledgementTimestamp);
} else {
startFlashing();
}
});
showAcknowledgementDialog(setAcknowledgementTimestamp);
} else {
startFlashing();
}
}
function showAcknowledgementDialog(acknowledgementCallback) {
@ -1306,8 +1294,8 @@ firmware_flasher.initialize = function (callback) {
if (status) {
const catch_new_port = function () {
PortHandler.port_detected('flash_detected_device', function (result) {
const port = result[0];
PortHandler.port_detected('flash_detected_device', function (resultPort) {
const port = resultPort[0];
if (!GUI.connect_lock) {
GUI.log(i18n.getMessage('firmwareFlasherFlashTrigger', [port]));

View File

@ -99,18 +99,17 @@ logging.initialize = function (callback) {
}
});
ConfigStorage.get('logging_file_entry', function (result) {
if (result.logging_file_entry) {
chrome.fileSystem.restoreEntry(result.logging_file_entry, function (entry) {
if (checkChromeRuntimeError()) {
return;
}
const result = ConfigStorage.get('logging_file_entry');
if (result.logging_file_entry) {
chrome.fileSystem.restoreEntry(result.logging_file_entry, function (entry) {
if (checkChromeRuntimeError()) {
return;
}
fileEntry = entry;
prepare_writer(true);
});
}
});
fileEntry = entry;
prepare_writer(true);
});
}
GUI.content_ready(callback);
}

View File

@ -559,22 +559,21 @@ TABS.motors.initialize = function (callback) {
});
// set refresh speeds according to configuration saved in storage
ConfigStorage.get(['motors_tab_sensor_settings', 'motors_tab_gyro_settings', 'motors_tab_accel_settings'], function (result) {
if (result.motors_tab_sensor_settings) {
$('.tab-motors select[name="sensor_choice"]').val(result.motors_tab_sensor_settings.sensor);
}
const result = ConfigStorage.get(['motors_tab_sensor_settings', 'motors_tab_gyro_settings', 'motors_tab_accel_settings']);
if (result.motors_tab_sensor_settings) {
$('.tab-motors select[name="sensor_choice"]').val(result.motors_tab_sensor_settings.sensor);
}
if (result.motors_tab_gyro_settings) {
TABS.motors.sensorGyroRate = result.motors_tab_gyro_settings.rate;
TABS.motors.sensorGyroScale = result.motors_tab_gyro_settings.scale;
}
if (result.motors_tab_gyro_settings) {
TABS.motors.sensorGyroRate = result.motors_tab_gyro_settings.rate;
TABS.motors.sensorGyroScale = result.motors_tab_gyro_settings.scale;
}
if (result.motors_tab_accel_settings) {
TABS.motors.sensorAccelRate = result.motors_tab_accel_settings.rate;
TABS.motors.sensorAccelScale = result.motors_tab_accel_settings.scale;
}
$('.tab-motors .sensor select:first').change();
});
if (result.motors_tab_accel_settings) {
TABS.motors.sensorAccelRate = result.motors_tab_accel_settings.rate;
TABS.motors.sensorAccelScale = result.motors_tab_accel_settings.scale;
}
$('.tab-motors .sensor select:first').change();
// Amperage
function power_data_pull() {

View File

@ -32,83 +32,78 @@ options.cleanup = function (callback) {
};
options.initShowWarnings = function () {
ConfigStorage.get('showPresetsWarningBackup', function (result) {
if (result.showPresetsWarningBackup) {
$('div.presetsWarningBackup input').prop('checked', true);
}
const result = ConfigStorage.get('showPresetsWarningBackup');
if (result.showPresetsWarningBackup) {
$('div.presetsWarningBackup input').prop('checked', true);
}
$('div.presetsWarningBackup input').change(function () {
const checked = $(this).is(':checked');
ConfigStorage.set({'showPresetsWarningBackup': checked});
}).change();
});
$('div.presetsWarningBackup input').change(function () {
const checked = $(this).is(':checked');
ConfigStorage.set({'showPresetsWarningBackup': checked});
}).change();
};
options.initPermanentExpertMode = function () {
ConfigStorage.get('permanentExpertMode', function (result) {
if (result.permanentExpertMode) {
$('div.permanentExpertMode input').prop('checked', true);
}
const result = ConfigStorage.get('permanentExpertMode');
if (result.permanentExpertMode) {
$('div.permanentExpertMode input').prop('checked', true);
}
$('div.permanentExpertMode input').change(function () {
const checked = $(this).is(':checked');
$('div.permanentExpertMode input').change(function () {
const checked = $(this).is(':checked');
ConfigStorage.set({'permanentExpertMode': checked});
ConfigStorage.set({'permanentExpertMode': checked});
$('input[name="expertModeCheckbox"]').prop('checked', checked).change();
}).change();
});
$('input[name="expertModeCheckbox"]').prop('checked', checked).change();
}).change();
};
options.initRememberLastTab = function () {
ConfigStorage.get('rememberLastTab', function (result) {
$('div.rememberLastTab input')
.prop('checked', !!result.rememberLastTab)
.change(function() { ConfigStorage.set({rememberLastTab: $(this).is(':checked')}); })
.change();
});
const result = ConfigStorage.get('rememberLastTab');
$('div.rememberLastTab input')
.prop('checked', !!result.rememberLastTab)
.change(function() { ConfigStorage.set({rememberLastTab: $(this).is(':checked')}); })
.change();
};
options.initCheckForConfiguratorUnstableVersions = function () {
ConfigStorage.get('checkForConfiguratorUnstableVersions', function (result) {
if (result.checkForConfiguratorUnstableVersions) {
$('div.checkForConfiguratorUnstableVersions input').prop('checked', true);
}
const result = ConfigStorage.get('checkForConfiguratorUnstableVersions');
if (result.checkForConfiguratorUnstableVersions) {
$('div.checkForConfiguratorUnstableVersions input').prop('checked', true);
}
$('div.checkForConfiguratorUnstableVersions input').change(function () {
const checked = $(this).is(':checked');
$('div.checkForConfiguratorUnstableVersions input').change(function () {
const checked = $(this).is(':checked');
ConfigStorage.set({'checkForConfiguratorUnstableVersions': checked});
ConfigStorage.set({'checkForConfiguratorUnstableVersions': checked});
checkForConfiguratorUpdates();
});
checkForConfiguratorUpdates();
});
};
options.initAnalyticsOptOut = function () {
ConfigStorage.get('analyticsOptOut', function (result) {
if (result.analyticsOptOut) {
$('div.analyticsOptOut input').prop('checked', true);
}
const result = ConfigStorage.get('analyticsOptOut');
if (result.analyticsOptOut) {
$('div.analyticsOptOut input').prop('checked', true);
}
$('div.analyticsOptOut input').change(function () {
const checked = $(this).is(':checked');
$('div.analyticsOptOut input').change(function () {
const checked = $(this).is(':checked');
ConfigStorage.set({'analyticsOptOut': checked});
ConfigStorage.set({'analyticsOptOut': checked});
checkSetupAnalytics(function (analyticsService) {
if (checked) {
analyticsService.sendEvent(analyticsService.EVENT_CATEGORIES.APPLICATION, 'OptOut');
}
checkSetupAnalytics(function (analyticsService) {
if (checked) {
analyticsService.sendEvent(analyticsService.EVENT_CATEGORIES.APPLICATION, 'OptOut');
}
analyticsService.setOptOut(checked);
analyticsService.setOptOut(checked);
if (!checked) {
analyticsService.sendEvent(analyticsService.EVENT_CATEGORIES.APPLICATION, 'OptIn');
}
});
}).change();
});
if (!checked) {
analyticsService.sendEvent(analyticsService.EVENT_CATEGORIES.APPLICATION, 'OptIn');
}
});
}).change();
};
options.initCliAutoComplete = function () {
@ -122,45 +117,53 @@ options.initCliAutoComplete = function () {
}).change();
};
options.initAutoConnectConnectionTimeout = function () {
const result = ConfigStorage.get('connectionTimeout');
if (result.connectionTimeout) {
$('#connectionTimeoutSelect').val(result.connectionTimeout);
}
$('#connectionTimeoutSelect').on('change', function () {
const value = parseInt($(this).val());
ConfigStorage.set({'connectionTimeout': value});
});
};
options.initShowAllSerialDevices = function() {
const showAllSerialDevicesElement = $('div.showAllSerialDevices input');
ConfigStorage.get('showAllSerialDevices', result => {
showAllSerialDevicesElement
.prop('checked', !!result.showAllSerialDevices)
.on('change', () => ConfigStorage.set({ showAllSerialDevices: showAllSerialDevicesElement.is(':checked') }))
.trigger('change');
});
const result = ConfigStorage.get('showAllSerialDevices');
showAllSerialDevicesElement
.prop('checked', !!result.showAllSerialDevices)
.on('change', () => ConfigStorage.set({ showAllSerialDevices: showAllSerialDevicesElement.is(':checked') }))
.trigger('change');
};
options.initShowVirtualMode = function() {
const showVirtualModeElement = $('div.showVirtualMode input');
ConfigStorage.get('showVirtualMode', result => {
showVirtualModeElement
.prop('checked', !!result.showVirtualMode)
.on('change', () => {
ConfigStorage.set({ showVirtualMode: showVirtualModeElement.is(':checked') });
PortHandler.initialPorts = false;
})
.trigger('change');
});
const result = ConfigStorage.get('showVirtualMode');
showVirtualModeElement
.prop('checked', !!result.showVirtualMode)
.on('change', () => {
ConfigStorage.set({ showVirtualMode: showVirtualModeElement.is(':checked') });
PortHandler.initialPorts = false;
})
.trigger('change');
};
options.initCordovaForceComputerUI = function () {
if (GUI.isCordova() && cordovaUI.canChangeUI) {
ConfigStorage.get('cordovaForceComputerUI', function (result) {
if (result.cordovaForceComputerUI) {
$('div.cordovaForceComputerUI input').prop('checked', true);
const result = ConfigStorage.get('cordovaForceComputerUI');
if (result.cordovaForceComputerUI) {
$('div.cordovaForceComputerUI input').prop('checked', true);
}
$('div.cordovaForceComputerUI input').change(function () {
const checked = $(this).is(':checked');
ConfigStorage.set({'cordovaForceComputerUI': checked});
if (typeof cordovaUI.set === 'function') {
cordovaUI.set();
}
$('div.cordovaForceComputerUI input').change(function () {
const checked = $(this).is(':checked');
ConfigStorage.set({'cordovaForceComputerUI': checked});
if (typeof cordovaUI.set === 'function') {
cordovaUI.set();
}
});
});
} else {
$('div.cordovaForceComputerUI').hide();

View File

@ -783,13 +783,12 @@ TABS.receiver.initialize = function (callback) {
GUI.interval_add('receiver_pull', get_rc_refresh_data, plotUpdateRate, true);
});
ConfigStorage.get('rx_refresh_rate', function (result) {
if (result.rxRefreshRate) {
rxRefreshRate.val(result.rxRefreshRate).change();
} else {
rxRefreshRate.change(); // start with default value
}
});
const result = ConfigStorage.get('rx_refresh_rate');
if (result.rxRefreshRate) {
rxRefreshRate.val(result.rxRefreshRate).change();
} else {
rxRefreshRate.change(); // start with default value
}
// Setup model for preview
tab.initModelPreview();

View File

@ -428,40 +428,39 @@ TABS.sensors.initialize = function (callback) {
}
});
ConfigStorage.get('sensor_settings', function (result) {
// set refresh speeds according to configuration saved in storage
if (result.sensor_settings) {
$('.tab-sensors select[name="gyro_refresh_rate"]').val(result.sensor_settings.rates.gyro);
$('.tab-sensors select[name="gyro_scale"]').val(result.sensor_settings.scales.gyro);
const result = ConfigStorage.get('sensor_settings');
// set refresh speeds according to configuration saved in storage
if (result.sensor_settings) {
$('.tab-sensors select[name="gyro_refresh_rate"]').val(result.sensor_settings.rates.gyro);
$('.tab-sensors select[name="gyro_scale"]').val(result.sensor_settings.scales.gyro);
$('.tab-sensors select[name="accel_refresh_rate"]').val(result.sensor_settings.rates.accel);
$('.tab-sensors select[name="accel_scale"]').val(result.sensor_settings.scales.accel);
$('.tab-sensors select[name="accel_refresh_rate"]').val(result.sensor_settings.rates.accel);
$('.tab-sensors select[name="accel_scale"]').val(result.sensor_settings.scales.accel);
$('.tab-sensors select[name="mag_refresh_rate"]').val(result.sensor_settings.rates.mag);
$('.tab-sensors select[name="mag_scale"]').val(result.sensor_settings.scales.mag);
$('.tab-sensors select[name="mag_refresh_rate"]').val(result.sensor_settings.rates.mag);
$('.tab-sensors select[name="mag_scale"]').val(result.sensor_settings.scales.mag);
$('.tab-sensors select[name="altitude_refresh_rate"]').val(result.sensor_settings.rates.altitude);
$('.tab-sensors select[name="sonar_refresh_rate"]').val(result.sensor_settings.rates.sonar);
$('.tab-sensors select[name="altitude_refresh_rate"]').val(result.sensor_settings.rates.altitude);
$('.tab-sensors select[name="sonar_refresh_rate"]').val(result.sensor_settings.rates.sonar);
$('.tab-sensors select[name="debug_refresh_rate"]').val(result.sensor_settings.rates.debug);
$('.tab-sensors select[name="debug_refresh_rate"]').val(result.sensor_settings.rates.debug);
// start polling data by triggering refresh rate change event
$('.tab-sensors .rate select:first').change();
} else {
// start polling immediatly (as there is no configuration saved in the storage)
$('.tab-sensors .rate select:first').change();
// start polling data by triggering refresh rate change event
$('.tab-sensors .rate select:first').change();
} else {
// start polling immediatly (as there is no configuration saved in the storage)
$('.tab-sensors .rate select:first').change();
}
const resultGraphs = ConfigStorage.get('graphs_enabled');
if (resultGraphs.graphs_enabled) {
const _checkboxes = $('.tab-sensors .info .checkboxes input');
for (let i = 0; i < resultGraphs.graphs_enabled.length; i++) {
_checkboxes.eq(i).not(':disabled').prop('checked', resultGraphs.graphs_enabled[i]).change();
}
ConfigStorage.get('graphs_enabled', function (resultGraphs) {
if (resultGraphs.graphs_enabled) {
const _checkboxes = $('.tab-sensors .info .checkboxes input');
for (let i = 0; i < resultGraphs.graphs_enabled.length; i++) {
_checkboxes.eq(i).not(':disabled').prop('checked', resultGraphs.graphs_enabled[i]).change();
}
} else {
$('.tab-sensors .info input:lt(4):not(:disabled)').prop('checked', true).change();
}
});
});
} else {
$('.tab-sensors .info input:lt(4):not(:disabled)').prop('checked', true).change();
}
// status data pulled via separate timer with static speed
GUI.interval_add('status_pull', function status_pull() {