1
0
Fork 0
mirror of https://github.com/betaflight/betaflight-configurator.git synced 2025-07-15 04:15:32 +03:00

Refactor config storage to use modules (#3189)

This commit is contained in:
Tomas Chmelevskij 2023-01-03 18:08:36 +01:00 committed by GitHub
parent e6cbc22f6b
commit 2a4deed7cf
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
15 changed files with 148 additions and 117 deletions

View file

@ -1,48 +1,70 @@
'use strict'; /**
* Gets one or more items from localStorage
* @param {string | string[]} key string or array of strings
* @returns {object}
*/
export function get(key) {
let result = {};
if (Array.isArray(key)) {
key.forEach(function (element) {
try {
result = { ...result, ...JSON.parse(localStorage.getItem(element)) };
} catch (e) {
console.error(e);
}
});
} else {
const keyValue = localStorage.getItem(key);
if (keyValue) {
try {
result = JSON.parse(keyValue);
} catch (e) {
console.error(e);
}
}
}
// idea here is to abstract around the use of chrome.storage.local as it functions differently from "localStorage" and IndexedDB return result;
// localStorage deals with strings, not objects, so the objects have been serialized. }
/**
* Save dictionary of key/value pairs to localStorage
* @param {object} input object which keys are strings and values are serializable objects
*/
export function set(input) {
Object.keys(input).forEach(function (element) {
const tmpObj = {};
tmpObj[element] = input[element];
try {
localStorage.setItem(element, JSON.stringify(tmpObj));
} catch (e) {
console.error(e);
}
});
}
/**
* Remove item from localStorage
* @param {string} item key to remove from storage
*/
export function remove(item) {
localStorage.removeItem(item);
}
/**
* Clear localStorage
*/
export function clear() {
localStorage.clear();
}
/**
* @deprecated this is a temporary solution to allow the use of the ConfigStorage module in old way
*/
const ConfigStorage = { const ConfigStorage = {
// key can be one string, or array of strings get,
get: function(key) { set,
let result = {}; remove,
if (Array.isArray(key)) { clear,
key.forEach(function (element) {
try {
result = {...result, ...JSON.parse(localStorage.getItem(element))};
} catch (e) {
console.error(e);
}
});
} else {
const keyValue = localStorage.getItem(key);
if (keyValue) {
try {
result = JSON.parse(keyValue);
} catch (e) {
console.error(e);
}
}
}
return result;
},
// set takes an object like {'userLanguageSelect':'DEFAULT'}
set: function(input) {
Object.keys(input).forEach(function (element) {
const tmpObj = {};
tmpObj[element] = input[element];
try {
localStorage.setItem(element, JSON.stringify(tmpObj));
} catch (e) {
console.error(e);
}
});
},
remove: function(item) {
localStorage.removeItem(item);
},
clear: function() {
localStorage.clear();
},
}; };
window.ConfigStorage = ConfigStorage;

View file

@ -1,3 +1,5 @@
import { get as getConfig } from './ConfigStorage';
window.TABS = {}; // filled by individual tab js file window.TABS = {}; // filled by individual tab js file
const GUI_MODES = { const GUI_MODES = {
@ -358,7 +360,7 @@ class GuiControl {
} }
} }
selectDefaultTabWhenConnected() { selectDefaultTabWhenConnected() {
const result = ConfigStorage.get(['rememberLastTab', 'lastTab']); const result = getConfig(['rememberLastTab', 'lastTab']);
const tab = result.rememberLastTab && result.lastTab ? result.lastTab : 'tab_setup'; const tab = result.rememberLastTab && result.lastTab ? result.lastTab : 'tab_setup';
$(`#tabs ul.mode-connected .${tab} a`).trigger('click'); $(`#tabs ul.mode-connected .${tab} a`).trigger('click');

View file

@ -1,6 +1,7 @@
import i18next from 'i18next'; import i18next from 'i18next';
import i18nextXHRBackend from 'i18next-xhr-backend'; import i18nextXHRBackend from 'i18next-xhr-backend';
import GUI from './gui.js'; import GUI from './gui.js';
import { get as getConfig, set as setConfig } from './ConfigStorage.js';
const i18n = {}; const i18n = {};
/* /*
@ -80,9 +81,7 @@ i18n.parseInputFile = function(data) {
}; };
i18n.changeLanguage = function(languageSelected) { i18n.changeLanguage = function(languageSelected) {
if (typeof ConfigStorage !== 'undefined') { setConfig({'userLanguageSelect': languageSelected});
ConfigStorage.set({'userLanguageSelect': languageSelected});
}
i18next.changeLanguage(getValidLocale(languageSelected)); i18next.changeLanguage(getValidLocale(languageSelected));
i18n.selectedLanguage = languageSelected; i18n.selectedLanguage = languageSelected;
GUI.log(i18n.getMessage('language_changed')); GUI.log(i18n.getMessage('language_changed'));
@ -192,13 +191,11 @@ i18n.localizePage = function(forceReTranslate) {
*/ */
function getStoredUserLocale(cb) { function getStoredUserLocale(cb) {
let userLanguage = 'DEFAULT'; let userLanguage = 'DEFAULT';
if (typeof ConfigStorage !== 'undefined') { const result = getConfig('userLanguageSelect');
const result = ConfigStorage.get('userLanguageSelect'); if (result.userLanguageSelect) {
if (result.userLanguageSelect) { userLanguage = result.userLanguageSelect;
userLanguage = result.userLanguageSelect;
}
i18n.selectedLanguage = userLanguage;
} }
i18n.selectedLanguage = userLanguage;
userLanguage = getValidLocale(userLanguage); userLanguage = getValidLocale(userLanguage);
cb(userLanguage); cb(userLanguage);
} }

View file

@ -1,6 +1,7 @@
import '../components/init.js'; import '../components/init.js';
import { i18n } from './localization.js'; import { i18n } from './localization.js';
import GUI from './gui.js'; import GUI from './gui.js';
import { get as getConfig, set as setConfig } from './ConfigStorage.js';
$(document).ready(function () { $(document).ready(function () {
@ -198,7 +199,7 @@ function startProcess() {
const tabNameWithoutPrefix = tabName.substring(4); const tabNameWithoutPrefix = tabName.substring(4);
if (tabNameWithoutPrefix !== "cli") { if (tabNameWithoutPrefix !== "cli") {
// Don't store 'cli' otherwise you can never connect to another tab. // Don't store 'cli' otherwise you can never connect to another tab.
ConfigStorage.set( setConfig(
{lastTab: tabName}, {lastTab: tabName},
); );
} }
@ -494,14 +495,14 @@ function startProcess() {
$("#log").removeClass('active'); $("#log").removeClass('active');
$("#tab-content-container").removeClass('logopen'); $("#tab-content-container").removeClass('logopen');
$("#scrollicon").removeClass('active'); $("#scrollicon").removeClass('active');
ConfigStorage.set({'logopen': false}); setConfig({'logopen': false});
state = false; state = false;
} else { } else {
$("#log").addClass('active'); $("#log").addClass('active');
$("#tab-content-container").addClass('logopen'); $("#tab-content-container").addClass('logopen');
$("#scrollicon").addClass('active'); $("#scrollicon").addClass('active');
ConfigStorage.set({'logopen': true}); setConfig({'logopen': true});
state = true; state = true;
} }
@ -509,12 +510,12 @@ function startProcess() {
$(this).data('state', state); $(this).data('state', state);
}); });
let result = ConfigStorage.get('logopen'); let result = getConfig('logopen');
if (result.logopen) { if (result.logopen) {
$("#showlog").trigger('click'); $("#showlog").trigger('click');
} }
result = ConfigStorage.get('permanentExpertMode'); result = getConfig('permanentExpertMode');
const expertModeCheckbox = 'input[name="expertModeCheckbox"]'; const expertModeCheckbox = 'input[name="expertModeCheckbox"]';
if (result.permanentExpertMode) { if (result.permanentExpertMode) {
$(expertModeCheckbox).prop('checked', true); $(expertModeCheckbox).prop('checked', true);
@ -534,10 +535,10 @@ function startProcess() {
$(expertModeCheckbox).trigger("change"); $(expertModeCheckbox).trigger("change");
result = ConfigStorage.get('cliAutoComplete'); result = getConfig('cliAutoComplete');
CliAutoComplete.setEnabled(typeof result.cliAutoComplete === "undefined" || result.cliAutoComplete); // On by default CliAutoComplete.setEnabled(typeof result.cliAutoComplete === "undefined" || result.cliAutoComplete); // On by default
result = ConfigStorage.get('darkTheme'); result = getConfig('darkTheme');
if (result.darkTheme === undefined || typeof result.darkTheme !== "number") { if (result.darkTheme === undefined || typeof result.darkTheme !== "number") {
// sets dark theme to auto if not manually changed // sets dark theme to auto if not manually changed
setDarkTheme(2); setDarkTheme(2);
@ -575,7 +576,7 @@ function checkForConfiguratorUpdates() {
} }
function notifyOutdatedVersion(releaseData) { function notifyOutdatedVersion(releaseData) {
const result = ConfigStorage.get('checkForConfiguratorUnstableVersions'); const result = getConfig('checkForConfiguratorUnstableVersions');
let showUnstableReleases = false; let showUnstableReleases = false;
if (result.checkForConfiguratorUnstableVersions) { if (result.checkForConfiguratorUnstableVersions) {
showUnstableReleases = true; showUnstableReleases = true;

View file

@ -1,5 +1,6 @@
import { i18n } from '../localization'; import { i18n } from '../localization';
import GUI from '../gui'; import GUI from '../gui';
import { get as getConfig, set as setConfig } from '../ConfigStorage';
const auxiliary = {}; const auxiliary = {};
@ -529,11 +530,11 @@ auxiliary.initialize = function (callback) {
} }
let hideUnusedModes = false; let hideUnusedModes = false;
const result = ConfigStorage.get('hideUnusedModes'); const result = getConfig('hideUnusedModes');
$("input#switch-toggle-unused") $("input#switch-toggle-unused")
.change(function() { .change(function() {
hideUnusedModes = $(this).prop("checked"); hideUnusedModes = $(this).prop("checked");
ConfigStorage.set({ hideUnusedModes: hideUnusedModes }); setConfig({ hideUnusedModes: hideUnusedModes });
update_ui(); update_ui();
}) })
.prop("checked", !!result.hideUnusedModes) .prop("checked", !!result.hideUnusedModes)

View file

@ -1,5 +1,6 @@
import { i18n } from '../localization'; import { i18n } from '../localization';
import GUI from '../gui'; import GUI from '../gui';
import { get as getConfig, set as setConfig } from '../ConfigStorage';
const firmware_flasher = { const firmware_flasher = {
targets: null, targets: null,
@ -218,11 +219,11 @@ firmware_flasher.initialize = function (callback) {
buildBuildTypeOptionsList(); buildBuildTypeOptionsList();
buildType_e.val(0).trigger('change'); buildType_e.val(0).trigger('change');
ConfigStorage.set({'selected_expert_mode': expertModeChecked}); setConfig({'selected_expert_mode': expertModeChecked});
} }
const expertMode_e = $('.tab-firmware_flasher input.expert_mode'); const expertMode_e = $('.tab-firmware_flasher input.expert_mode');
const expertMode = ConfigStorage.get('selected_expert_mode'); const expertMode = getConfig('selected_expert_mode');
expertMode_e.prop('checked', expertMode.selected_expert_mode ?? false); expertMode_e.prop('checked', expertMode.selected_expert_mode ?? false);
$('input.show_development_releases').change(showOrHideBuildTypes).change(); $('input.show_development_releases').change(showOrHideBuildTypes).change();
expertMode_e.change(showOrHideExpertMode).change(); expertMode_e.change(showOrHideExpertMode).change();
@ -248,7 +249,7 @@ firmware_flasher.initialize = function (callback) {
} }
} }
ConfigStorage.set({'selected_build_type': build_type}); setConfig({'selected_build_type': build_type});
}); });
function selectFirmware(release) { function selectFirmware(release) {
@ -592,7 +593,7 @@ firmware_flasher.initialize = function (callback) {
detectBoardElement.toggleClass('disabled', isButtonDisabled); detectBoardElement.toggleClass('disabled', isButtonDisabled);
} }
let result = ConfigStorage.get('erase_chip'); let result = getConfig('erase_chip');
if (result.erase_chip) { if (result.erase_chip) {
$('input.erase_chip').prop('checked', true); $('input.erase_chip').prop('checked', true);
} else { } else {
@ -600,21 +601,21 @@ firmware_flasher.initialize = function (callback) {
} }
$('input.erase_chip').change(function () { $('input.erase_chip').change(function () {
ConfigStorage.set({'erase_chip': $(this).is(':checked')}); setConfig({'erase_chip': $(this).is(':checked')});
}).change(); }).change();
result = ConfigStorage.get('show_development_releases'); result = getConfig('show_development_releases');
$('input.show_development_releases') $('input.show_development_releases')
.prop('checked', result.show_development_releases) .prop('checked', result.show_development_releases)
.change(function () { .change(function () {
ConfigStorage.set({'show_development_releases': $(this).is(':checked')}); setConfig({'show_development_releases': $(this).is(':checked')});
}).change(); }).change();
result = ConfigStorage.get('selected_build_type'); result = getConfig('selected_build_type');
// ensure default build type is selected // ensure default build type is selected
buildType_e.val(result.selected_build_type || 0).trigger('change'); buildType_e.val(result.selected_build_type || 0).trigger('change');
result = ConfigStorage.get('no_reboot_sequence'); result = getConfig('no_reboot_sequence');
if (result.no_reboot_sequence) { if (result.no_reboot_sequence) {
$('input.updating').prop('checked', true); $('input.updating').prop('checked', true);
$('.flash_on_connect_wrapper').show(); $('.flash_on_connect_wrapper').show();
@ -633,12 +634,12 @@ firmware_flasher.initialize = function (callback) {
$('.flash_on_connect_wrapper').hide(); $('.flash_on_connect_wrapper').hide();
} }
ConfigStorage.set({'no_reboot_sequence': status}); setConfig({'no_reboot_sequence': status});
}); });
$('input.updating').change(); $('input.updating').change();
result = ConfigStorage.get('flash_manual_baud'); result = getConfig('flash_manual_baud');
if (result.flash_manual_baud) { if (result.flash_manual_baud) {
$('input.flash_manual_baud').prop('checked', true); $('input.flash_manual_baud').prop('checked', true);
} else { } else {
@ -655,18 +656,18 @@ firmware_flasher.initialize = function (callback) {
// bind UI hook so the status is saved on change // bind UI hook so the status is saved on change
$('input.flash_manual_baud').change(function() { $('input.flash_manual_baud').change(function() {
const status = $(this).is(':checked'); const status = $(this).is(':checked');
ConfigStorage.set({'flash_manual_baud': status}); setConfig({'flash_manual_baud': status});
}); });
$('input.flash_manual_baud').change(); $('input.flash_manual_baud').change();
result = ConfigStorage.get('flash_manual_baud_rate'); result = getConfig('flash_manual_baud_rate');
$('#flash_manual_baud_rate').val(result.flash_manual_baud_rate); $('#flash_manual_baud_rate').val(result.flash_manual_baud_rate);
// bind UI hook so the status is saved on change // bind UI hook so the status is saved on change
$('#flash_manual_baud_rate').change(function() { $('#flash_manual_baud_rate').change(function() {
const baud = parseInt($('#flash_manual_baud_rate').val()); const baud = parseInt($('#flash_manual_baud_rate').val());
ConfigStorage.set({'flash_manual_baud_rate': baud}); setConfig({'flash_manual_baud_rate': baud});
}); });
$('input.flash_manual_baud_rate').change(); $('input.flash_manual_baud_rate').change();

View file

@ -1,4 +1,5 @@
import GUI from '../gui'; import GUI from '../gui';
import { i18n } from '../localization';
const help = {}; const help = {};
help.initialize = function (callback) { help.initialize = function (callback) {

View file

@ -1,4 +1,5 @@
import GUI from '../gui'; import GUI from '../gui';
import { i18n } from '../localization';
const landing = {}; const landing = {};
landing.initialize = function (callback) { landing.initialize = function (callback) {

View file

@ -1,5 +1,6 @@
import { millitime } from '../utils/common.js'; import { millitime } from '../utils/common.js';
import GUI from '../gui'; import GUI from '../gui';
import { get as getConfig, set as setConfig } from '../ConfigStorage';
const logging = {}; const logging = {};
logging.initialize = function (callback) { logging.initialize = function (callback) {
@ -100,7 +101,7 @@ logging.initialize = function (callback) {
} }
}); });
const result = ConfigStorage.get('logging_file_entry'); const result = getConfig('logging_file_entry');
if (result.logging_file_entry) { if (result.logging_file_entry) {
chrome.fileSystem.restoreEntry(result.logging_file_entry, function (entry) { chrome.fileSystem.restoreEntry(result.logging_file_entry, function (entry) {
if (checkChromeRuntimeError()) { if (checkChromeRuntimeError()) {
@ -263,7 +264,7 @@ logging.initialize = function (callback) {
fileEntry = fileEntryWritable; fileEntry = fileEntryWritable;
// save entry for next use // save entry for next use
ConfigStorage.set({'logging_file_entry': chrome.fileSystem.retainEntry(fileEntry)}); setConfig({'logging_file_entry': chrome.fileSystem.retainEntry(fileEntry)});
// reset sample counter in UI // reset sample counter in UI
$('.samples').text(0); $('.samples').text(0);

View file

@ -1,5 +1,6 @@
import { i18n } from "../localization"; import { i18n } from "../localization";
import GUI from '../gui'; import GUI from '../gui';
import { get as getConfig, set as setConfig } from '../ConfigStorage';
const motors = { const motors = {
previousDshotBidir: null, previousDshotBidir: null,
@ -450,7 +451,7 @@ motors.initialize = async function (callback) {
$('.tab-motors .sensor select').change(function(){ $('.tab-motors .sensor select').change(function(){
TABS.motors.sensor = $('.tab-motors select[name="sensor_choice"]').val(); TABS.motors.sensor = $('.tab-motors select[name="sensor_choice"]').val();
ConfigStorage.set({'motors_tab_sensor_settings': {'sensor': TABS.motors.sensor}}); setConfig({'motors_tab_sensor_settings': {'sensor': TABS.motors.sensor}});
switch(TABS.motors.sensor){ switch(TABS.motors.sensor){
case "gyro": case "gyro":
@ -476,7 +477,7 @@ motors.initialize = async function (callback) {
switch(TABS.motors.sensor) { switch(TABS.motors.sensor) {
case "gyro": case "gyro":
ConfigStorage.set({'motors_tab_gyro_settings': {'rate': rate, 'scale': scale}}); setConfig({'motors_tab_gyro_settings': {'rate': rate, 'scale': scale}});
TABS.motors.sensorGyroRate = rate; TABS.motors.sensorGyroRate = rate;
TABS.motors.sensorGyroScale = scale; TABS.motors.sensorGyroScale = scale;
@ -487,7 +488,7 @@ motors.initialize = async function (callback) {
}, rate, true); }, rate, true);
break; break;
case "accel": case "accel":
ConfigStorage.set({'motors_tab_accel_settings': {'rate': rate, 'scale': scale}}); setConfig({'motors_tab_accel_settings': {'rate': rate, 'scale': scale}});
TABS.motors.sensorAccelRate = rate; TABS.motors.sensorAccelRate = rate;
TABS.motors.sensorAccelScale = scale; TABS.motors.sensorAccelScale = scale;
accelHelpers = initGraphHelpers('#graph', samplesAccel, [-scale, scale]); accelHelpers = initGraphHelpers('#graph', samplesAccel, [-scale, scale]);
@ -560,7 +561,7 @@ motors.initialize = async function (callback) {
}); });
// set refresh speeds according to configuration saved in storage // set refresh speeds according to configuration saved in storage
const result = ConfigStorage.get(['motors_tab_sensor_settings', 'motors_tab_gyro_settings', 'motors_tab_accel_settings']); const result = getConfig(['motors_tab_sensor_settings', 'motors_tab_gyro_settings', 'motors_tab_accel_settings']);
if (result.motors_tab_sensor_settings) { if (result.motors_tab_sensor_settings) {
$('.tab-motors select[name="sensor_choice"]').val(result.motors_tab_sensor_settings.sensor); $('.tab-motors select[name="sensor_choice"]').val(result.motors_tab_sensor_settings.sensor);
} }

View file

@ -1,5 +1,6 @@
import { i18n } from '../localization'; import { i18n } from '../localization';
import GUI from '../gui'; import GUI from '../gui';
import { get as getConfig, set as setConfig } from '../ConfigStorage';
const options = {}; const options = {};
options.initialize = function (callback) { options.initialize = function (callback) {
@ -32,19 +33,19 @@ options.cleanup = function (callback) {
}; };
options.initShowWarnings = function () { options.initShowWarnings = function () {
const result = ConfigStorage.get('showPresetsWarningBackup'); const result = getConfig('showPresetsWarningBackup');
if (result.showPresetsWarningBackup) { if (result.showPresetsWarningBackup) {
$('div.presetsWarningBackup input').prop('checked', true); $('div.presetsWarningBackup input').prop('checked', true);
} }
$('div.presetsWarningBackup input').change(function () { $('div.presetsWarningBackup input').change(function () {
const checked = $(this).is(':checked'); const checked = $(this).is(':checked');
ConfigStorage.set({'showPresetsWarningBackup': checked}); setConfig({'showPresetsWarningBackup': checked});
}).change(); }).change();
}; };
options.initPermanentExpertMode = function () { options.initPermanentExpertMode = function () {
const result = ConfigStorage.get('permanentExpertMode'); const result = getConfig('permanentExpertMode');
if (result.permanentExpertMode) { if (result.permanentExpertMode) {
$('div.permanentExpertMode input').prop('checked', true); $('div.permanentExpertMode input').prop('checked', true);
} }
@ -52,22 +53,22 @@ options.initPermanentExpertMode = function () {
$('div.permanentExpertMode input').change(function () { $('div.permanentExpertMode input').change(function () {
const checked = $(this).is(':checked'); const checked = $(this).is(':checked');
ConfigStorage.set({'permanentExpertMode': checked}); setConfig({'permanentExpertMode': checked});
$('input[name="expertModeCheckbox"]').prop('checked', checked).change(); $('input[name="expertModeCheckbox"]').prop('checked', checked).change();
}).change(); }).change();
}; };
options.initRememberLastTab = function () { options.initRememberLastTab = function () {
const result = ConfigStorage.get('rememberLastTab'); const result = getConfig('rememberLastTab');
$('div.rememberLastTab input') $('div.rememberLastTab input')
.prop('checked', !!result.rememberLastTab) .prop('checked', !!result.rememberLastTab)
.change(function() { ConfigStorage.set({rememberLastTab: $(this).is(':checked')}); }) .change(function() { setConfig({rememberLastTab: $(this).is(':checked')}); })
.change(); .change();
}; };
options.initCheckForConfiguratorUnstableVersions = function () { options.initCheckForConfiguratorUnstableVersions = function () {
const result = ConfigStorage.get('checkForConfiguratorUnstableVersions'); const result = getConfig('checkForConfiguratorUnstableVersions');
if (result.checkForConfiguratorUnstableVersions) { if (result.checkForConfiguratorUnstableVersions) {
$('div.checkForConfiguratorUnstableVersions input').prop('checked', true); $('div.checkForConfiguratorUnstableVersions input').prop('checked', true);
} }
@ -75,7 +76,7 @@ options.initCheckForConfiguratorUnstableVersions = function () {
$('div.checkForConfiguratorUnstableVersions input').change(function () { $('div.checkForConfiguratorUnstableVersions input').change(function () {
const checked = $(this).is(':checked'); const checked = $(this).is(':checked');
ConfigStorage.set({'checkForConfiguratorUnstableVersions': checked}); setConfig({'checkForConfiguratorUnstableVersions': checked});
checkForConfiguratorUpdates(); checkForConfiguratorUpdates();
}); });
@ -87,47 +88,47 @@ options.initCliAutoComplete = function () {
.change(function () { .change(function () {
const checked = $(this).is(':checked'); const checked = $(this).is(':checked');
ConfigStorage.set({'cliAutoComplete': checked}); setConfig({'cliAutoComplete': checked});
CliAutoComplete.setEnabled(checked); CliAutoComplete.setEnabled(checked);
}).change(); }).change();
}; };
options.initAutoConnectConnectionTimeout = function () { options.initAutoConnectConnectionTimeout = function () {
const result = ConfigStorage.get('connectionTimeout'); const result = getConfig('connectionTimeout');
if (result.connectionTimeout) { if (result.connectionTimeout) {
$('#connectionTimeoutSelect').val(result.connectionTimeout); $('#connectionTimeoutSelect').val(result.connectionTimeout);
} }
$('#connectionTimeoutSelect').on('change', function () { $('#connectionTimeoutSelect').on('change', function () {
const value = parseInt($(this).val()); const value = parseInt($(this).val());
ConfigStorage.set({'connectionTimeout': value}); setConfig({'connectionTimeout': value});
}); });
}; };
options.initShowAllSerialDevices = function() { options.initShowAllSerialDevices = function() {
const showAllSerialDevicesElement = $('div.showAllSerialDevices input'); const showAllSerialDevicesElement = $('div.showAllSerialDevices input');
const result = ConfigStorage.get('showAllSerialDevices'); const result = getConfig('showAllSerialDevices');
showAllSerialDevicesElement showAllSerialDevicesElement
.prop('checked', !!result.showAllSerialDevices) .prop('checked', !!result.showAllSerialDevices)
.on('change', () => { .on('change', () => {
ConfigStorage.set({ showAllSerialDevices: showAllSerialDevicesElement.is(':checked') }); setConfig({ showAllSerialDevices: showAllSerialDevicesElement.is(':checked') });
PortHandler.reinitialize(); PortHandler.reinitialize();
}); });
}; };
options.initShowVirtualMode = function() { options.initShowVirtualMode = function() {
const showVirtualModeElement = $('div.showVirtualMode input'); const showVirtualModeElement = $('div.showVirtualMode input');
const result = ConfigStorage.get('showVirtualMode'); const result = getConfig('showVirtualMode');
showVirtualModeElement showVirtualModeElement
.prop('checked', !!result.showVirtualMode) .prop('checked', !!result.showVirtualMode)
.on('change', () => { .on('change', () => {
ConfigStorage.set({ showVirtualMode: showVirtualModeElement.is(':checked') }); setConfig({ showVirtualMode: showVirtualModeElement.is(':checked') });
PortHandler.reinitialize(); PortHandler.reinitialize();
}); });
}; };
options.initCordovaForceComputerUI = function () { options.initCordovaForceComputerUI = function () {
if (GUI.isCordova() && cordovaUI.canChangeUI) { if (GUI.isCordova() && cordovaUI.canChangeUI) {
const result = ConfigStorage.get('cordovaForceComputerUI'); const result = getConfig('cordovaForceComputerUI');
if (result.cordovaForceComputerUI) { if (result.cordovaForceComputerUI) {
$('div.cordovaForceComputerUI input').prop('checked', true); $('div.cordovaForceComputerUI input').prop('checked', true);
} }
@ -135,7 +136,7 @@ options.initCordovaForceComputerUI = function () {
$('div.cordovaForceComputerUI input').change(function () { $('div.cordovaForceComputerUI input').change(function () {
const checked = $(this).is(':checked'); const checked = $(this).is(':checked');
ConfigStorage.set({'cordovaForceComputerUI': checked}); setConfig({'cordovaForceComputerUI': checked});
if (typeof cordovaUI.set === 'function') { if (typeof cordovaUI.set === 'function') {
cordovaUI.set(); cordovaUI.set();
@ -152,7 +153,7 @@ options.initDarkTheme = function () {
.change(function () { .change(function () {
const value = parseInt($(this).val()); const value = parseInt($(this).val());
ConfigStorage.set({'darkTheme': value}); setConfig({'darkTheme': value});
setDarkTheme(value); setDarkTheme(value);
}).change(); }).change();
}; };

View file

@ -1,7 +1,8 @@
import { i18n } from "../localization"; import { i18n } from "../localization";
import GUI from '../gui'; import GUI from '../gui';
import { get as getConfig, set as setConfig } from '../ConfigStorage';
import { MD5 } from 'crypto-es/lib/md5.js'; import CryptoES from 'crypto-es';
const receiver = { const receiver = {
rateChartHeight: 117, rateChartHeight: 117,
@ -15,16 +16,16 @@ receiver.initialize = function (callback) {
GUI.active_tab = 'receiver'; GUI.active_tab = 'receiver';
function lookup_elrs_passphrase(uidString) { function lookup_elrs_passphrase(uidString) {
const passphraseMap = ConfigStorage.get('passphrase_map').passphrase_map || {}; const passphraseMap = getConfig('passphrase_map').passphrase_map || {};
return passphraseMap[uidString] ?? 0; return passphraseMap[uidString] ?? 0;
} }
function save_elrs_passphrase(uidString, passphrase) { function save_elrs_passphrase(uidString, passphrase) {
const passphraseMap = ConfigStorage.get('passphrase_map').passphrase_map ?? {}; const passphraseMap = getConfig('passphrase_map').passphrase_map ?? {};
passphraseMap[uidString] = passphrase; passphraseMap[uidString] = passphrase;
ConfigStorage.set({'passphrase_map': passphraseMap}); setConfig({'passphrase_map': passphraseMap});
} }
function elrs_passphrase_to_bytes(text) { function elrs_passphrase_to_bytes(text) {
@ -32,7 +33,7 @@ receiver.initialize = function (callback) {
if (text) { if (text) {
const bindingPhraseFull = `-DMY_BINDING_PHRASE="${text}"`; const bindingPhraseFull = `-DMY_BINDING_PHRASE="${text}"`;
const hash = MD5(bindingPhraseFull).toString(); const hash = CryptoES.MD5(bindingPhraseFull).toString();
uidBytes = Uint8Array.from(Buffer.from(hash, 'hex')).subarray(0, 6); uidBytes = Uint8Array.from(Buffer.from(hash, 'hex')).subarray(0, 6);
} }
@ -659,7 +660,7 @@ receiver.initialize = function (callback) {
plotUpdateRate = parseInt($(this).val(), 10); plotUpdateRate = parseInt($(this).val(), 10);
// save update rate // save update rate
ConfigStorage.set({'rx_refresh_rate': plotUpdateRate}); setConfig({'rx_refresh_rate': plotUpdateRate});
function get_rc_refresh_data() { function get_rc_refresh_data() {
MSP.send_message(MSPCodes.MSP_RC, false, false, update_ui); MSP.send_message(MSPCodes.MSP_RC, false, false, update_ui);
@ -769,7 +770,7 @@ receiver.initialize = function (callback) {
GUI.interval_add('receiver_pull', get_rc_refresh_data, plotUpdateRate, true); GUI.interval_add('receiver_pull', get_rc_refresh_data, plotUpdateRate, true);
}); });
const result = ConfigStorage.get('rx_refresh_rate'); const result = getConfig('rx_refresh_rate');
if (result.rxRefreshRate) { if (result.rxRefreshRate) {
rxRefreshRate.val(result.rxRefreshRate).change(); rxRefreshRate.val(result.rxRefreshRate).change();
} else { } else {

View file

@ -1,5 +1,6 @@
import { i18n } from "../localization"; import { i18n } from "../localization";
import GUI from '../gui'; import GUI from '../gui';
import { get as getConfig, set as setConfig } from '../ConfigStorage';
const sensors = {}; const sensors = {};
sensors.initialize = function (callback) { sensors.initialize = function (callback) {
@ -239,7 +240,7 @@ sensors.initialize = function (callback) {
$('.tab-sensors .rate select:first').change(); $('.tab-sensors .rate select:first').change();
ConfigStorage.set({'graphs_enabled': _checkboxes}); setConfig({'graphs_enabled': _checkboxes});
}); });
// Always start with default/empty sensor data array, clean slate all // Always start with default/empty sensor data array, clean slate all
@ -317,7 +318,7 @@ sensors.initialize = function (callback) {
const fastest = d3.min([rates.gyro, rates.accel, rates.mag]); const fastest = d3.min([rates.gyro, rates.accel, rates.mag]);
// store current/latest refresh rates in the storage // store current/latest refresh rates in the storage
ConfigStorage.set({'sensor_settings': {'rates': rates, 'scales': scales}}); setConfig({'sensor_settings': {'rates': rates, 'scales': scales}});
// re-initialize domains with new scales // re-initialize domains with new scales
gyroHelpers = initGraphHelpers('#gyro', samples_gyro_i, [-scales.gyro, scales.gyro]); gyroHelpers = initGraphHelpers('#gyro', samples_gyro_i, [-scales.gyro, scales.gyro]);
@ -424,7 +425,7 @@ sensors.initialize = function (callback) {
} }
}); });
const result = ConfigStorage.get('sensor_settings'); const result = getConfig('sensor_settings');
// set refresh speeds according to configuration saved in storage // set refresh speeds according to configuration saved in storage
if (result.sensor_settings) { if (result.sensor_settings) {
$('.tab-sensors select[name="gyro_refresh_rate"]').val(result.sensor_settings.rates.gyro); $('.tab-sensors select[name="gyro_refresh_rate"]').val(result.sensor_settings.rates.gyro);
@ -448,7 +449,7 @@ sensors.initialize = function (callback) {
$('.tab-sensors .rate select:first').change(); $('.tab-sensors .rate select:first').change();
} }
const resultGraphs = ConfigStorage.get('graphs_enabled'); const resultGraphs = getConfig('graphs_enabled');
if (resultGraphs.graphs_enabled) { if (resultGraphs.graphs_enabled) {
const _checkboxes = $('.tab-sensors .info .checkboxes input'); const _checkboxes = $('.tab-sensors .info .checkboxes input');
for (let i = 0; i < resultGraphs.graphs_enabled.length; i++) { for (let i = 0; i < resultGraphs.graphs_enabled.length; i++) {

View file

@ -82,7 +82,6 @@
<script type="text/javascript" src="./js/utils/VtxDeviceStatus/TrampDeviceStatus.js"></script> <script type="text/javascript" src="./js/utils/VtxDeviceStatus/TrampDeviceStatus.js"></script>
<script type="text/javascript" src="./js/utils/VtxDeviceStatus/SmartAudioDeviceStatus.js"></script> <script type="text/javascript" src="./js/utils/VtxDeviceStatus/SmartAudioDeviceStatus.js"></script>
<script type="text/javascript" src="./js/utils/VtxDeviceStatus/Rtc6705DeviceStatus.js"></script> <script type="text/javascript" src="./js/utils/VtxDeviceStatus/Rtc6705DeviceStatus.js"></script>
<script type="text/javascript" src="./js/ConfigStorage.js"></script>
<script type="text/javascript" src="./js/SessionStorage.js"></script> <script type="text/javascript" src="./js/SessionStorage.js"></script>
<script type="text/javascript" src="./js/data_storage.js"></script> <script type="text/javascript" src="./js/data_storage.js"></script>
<script type="text/javascript" src="./js/fc.js"></script> <script type="text/javascript" src="./js/fc.js"></script>

View file

@ -1,4 +1,5 @@
import GUI from '../../js/gui'; import GUI from '../../js/gui';
import { get as getConfig, set as setConfig } from '../../js/ConfigStorage';
import { favoritePresets } from './FavoritePresets'; import { favoritePresets } from './FavoritePresets';
@ -174,11 +175,11 @@ presets.enableSaveCancelButtons = function (isEnabled) {
presets.onButtonHideBackupWarningClick = function() { presets.onButtonHideBackupWarningClick = function() {
this._domWarningBackup.toggle(false); this._domWarningBackup.toggle(false);
ConfigStorage.set({ 'showPresetsWarningBackup': false }); setConfig({ 'showPresetsWarningBackup': false });
}; };
presets.setupBackupWarning = function() { presets.setupBackupWarning = function() {
const obj = ConfigStorage.get('showPresetsWarningBackup'); const obj = getConfig('showPresetsWarningBackup');
if (obj.showPresetsWarningBackup === undefined) { if (obj.showPresetsWarningBackup === undefined) {
obj.showPresetsWarningBackup = true; obj.showPresetsWarningBackup = true;
} }