1
0
Fork 0
mirror of https://github.com/iNavFlight/inav-configurator.git synced 2025-07-13 11:29:53 +03:00

Convert to CommonJS Modules Part 3

This commit is contained in:
Scavanger 2024-04-18 15:39:19 -03:00
parent ca13eefa1b
commit 06a4d8b0c8
74 changed files with 1949 additions and 10259 deletions

View file

@ -67,7 +67,6 @@ sudo mv inav-configurator.desktop /usr/share/applications/
``` ```
10. Make the following files executable: 10. Make the following files executable:
* inav-configurator `chmod +x /opt/inav/inav-configurator/inav-configurator` * inav-configurator `chmod +x /opt/inav/inav-configurator/inav-configurator`
* (5.0.0+) chrome_crashpad_handler `chmod +x /opt/inav/inav-configurator/chrome_crashpad_handler`
11. Run the INAV Configurator app from the unpacked folder `/opt/inav/inav-configurator/inav-configurator` 11. Run the INAV Configurator app from the unpacked folder `/opt/inav/inav-configurator/inav-configurator`
### Mac ### Mac
@ -83,7 +82,7 @@ For local development, the **node.js** build system is used.
1. Install node.js 1. Install node.js
1. From the project folder run `npm install` 1. From the project folder run `npm install`
1. To build the JS and CSS files and start the configurator: 1. To build the and start the configurator:
- Run `npm start`. - Run `npm start`.
To build the App run `npm run make` to build for your platform. To build the App run `npm run make` to build for your platform.
@ -94,7 +93,7 @@ Options:
See [Electron Forge CLI Documentation](https://www.electronforge.io/cli#options-2) for details See [Electron Forge CLI Documentation](https://www.electronforge.io/cli#options-2) for details
Example (note the double -- ): Example (note the double -- ):
``` npm start -- --arch="ia32 ``` ``` npm run make -- --arch="x64" ```
### Running with debug | Inspector ### Running with debug | Inspector

View file

@ -1,756 +0,0 @@
'use strict';
var child_process = require('child_process');
var fs = require('fs');
var path = require('path');
var minimist = require('minimist');
var archiver = require('archiver');
var del = require('del');
var NwBuilder = require('nw-builder');
var semver = require('semver');
var gulp = require('gulp');
var concat = require('gulp-concat');
const commandExistsSync = require('command-exists').sync;
// Each key in the *sources* variable must be an array of
// the source files that will be combined into a single
// file and stored in *outputDir*. Each key in *sources*
// must be also present in *output*, whose value indicates
// the filename for the output file which combines the
// contents of the source files.
//
// Keys must be camel cased and end with either 'Css' or
// 'Js' (e.g. someSourcesCss or someSourcesJs). For each
// key, a build task will be generated named by prepending
// 'build-' and converting the key to dash-separated words
// (e.g. someSourcesCss will generate build-some-sources-css).
//
// Tasks with names ending with '-js' will be executed by the
// build-all-js task, while the ones ending with '-css' will
// be done by build-all-css. There's also a build task which
// runs both build-all-css and build-all-js.
//
// The watch task will monitor any files mentioned in the *sources*
// variable and regenerate the corresponding output file when
// they change.
//
// See README.md for details on the other tasks.
var sources = {};
sources.css = [
'./main.css',
'./js/libraries/jquery.nouislider.min.css',
'./js/libraries/jquery.nouislider.pips.min.css',
'./js/libraries/flightindicators.css',
'./src/css/tabs/*.css',
'./src/css/opensans_webfontkit/fonts.css',
'./src/css/font-awesome/css/font-awesome.css',
'./src/css/dropdown-lists/css/style_lists.css',
'./js/libraries/switchery/switchery.css',
'./js/libraries/jbox/jBox.css',
'./node_modules/openlayers/dist/ol.css',
'./src/css/logic.css',
'./src/css/defaults_dialog.css',
'./src/css/groundstation.css',
];
sources.js = [
'./js/libraries/google-analytics-bundle.js',
'./node_modules/jquery/dist/jquery.min.js',
'./node_modules/jquery-ui-npm/jquery-ui.min.js',
'./node_modules/marked/lib/marked.js',
'./js/libraries/d3.min.js',
'./js/libraries/jquery.nouislider.all.min.js',
'./node_modules/three/build/three.min.js',
'./node_modules/three/examples/js/loaders/GLTFLoader.js',
'./node_modules/three/examples/js/controls/OrbitControls.js',
'./js/libraries/nw-dialog.js',
'./js/libraries/bundle_xml2js.js',
'./js/libraries/Projector.js',
'./js/libraries/CanvasRenderer.js',
'./js/libraries/jquery.flightindicators.js',
'./js/libraries/semver.js',
'./js/libraries/jbox/jBox.min.js',
'./js/libraries/switchery/switchery.js',
'./js/libraries/jquery.ba-throttle-debounce.js',
'./js/helpers.js',
'./node_modules/inflection/inflection.min.js',
'./node_modules/bluebird/js/browser/bluebird.min.js',
'./js/injected_methods.js',
'./js/intervals.js',
'./js/timeouts.js',
'./js/pid_controller.js',
'./js/simple_smooth_filter.js',
'./js/walking_average_filter.js',
'./js/gui.js',
'./js/serialPortHelper.js',
'./js/msp/MSPCodes.js',
'./js/msp/MSPHelper.js',
'./js/msp/MSPchainer.js',
'./js/port_handler.js',
'./js/connection/connection.js',
'./js/connection/connectionBle.js',
'./js/connection/connectionSerial.js',
'./js/connection/connectionTcp.js',
'./js/connection/connectionUdp.js',
'./js/servoMixRule.js',
'./js/motorMixRule.js',
'./js/logicCondition.js',
'./js/settings.js',
'./js/outputMapping.js',
'./js/model.js',
'./js/serial_backend.js',
'./js/data_storage.js',
'./js/fc.js',
'./js/msp.js',
'./js/protocols/stm32.js',
'./js/protocols/stm32usbdfu.js',
'./js/localization.js',
'./js/boards.js',
'./js/servoMixerRuleCollection.js',
'./js/motorMixerRuleCollection.js',
'./js/logicConditionsCollection.js',
'./js/logicConditionsStatus.js',
'./js/globalVariablesStatus.js',
'./js/programmingPid.js',
'./js/programmingPidCollection.js',
'./js/programmingPidStatus.js',
'./js/vtx.js',
'./main.js',
'./js/tabs.js',
'./tabs/*.js',
'./js/eventFrequencyAnalyzer.js',
'./js/periodicStatusUpdater.js',
'./js/serial_queue.js',
'./js/msp_balanced_interval.js',
'./tabs/advanced_tuning.js',
'./tabs/ez_tune.js',
'./js/peripherals.js',
'./js/appUpdater.js',
'./js/feature_framework.js',
'./js/defaults_dialog.js',
'./js/safehomeCollection.js',
'./js/safehome.js',
'./js/waypointCollection.js',
'./js/waypoint.js',
'./node_modules/openlayers/dist/ol.js',
'./js/libraries/plotly-latest.min.js',
'./js/sitl.js',
'./js/CliAutoComplete.js',
'./node_modules/jquery-textcomplete/dist/jquery.textcomplete.js',
'./js/fwApproach.js',
'./js/fwApproachCollection.js',
'./js/ltmDecoder.js',
'./js/groundstation.js'
];
sources.receiverCss = [
'./src/css/tabs/receiver_msp.css',
'./src/css/opensans_webfontkit/fonts.css',
'./js/libraries/jquery.nouislider.min.css',
'./js/libraries/jquery.nouislider.pips.min.css',
];
sources.receiverJs = [
'./node_modules/jquery/dist/jquery.min.js',
'./node_modules/jquery-ui-npm/jquery-ui.min.js',
'./js/libraries/jquery.nouislider.all.min.js',
'./tabs/receiver_msp.js'
];
sources.debugTraceJs = [
'./js/debug_trace.js'
];
sources.hexParserJs = [
'./js/workers/hex_parser.js',
];
var output = {
css: 'styles.css',
js: 'script.js',
receiverCss: 'receiver-msp.css',
receiverJs: 'receiver-msp.js',
debugTraceJs: 'debug-trace.js',
hexParserJs: 'hex_parser.js',
};
var outputDir = './build/';
var distDir = './dist/';
var appsDir = './apps/';
function get_task_name(key) {
return 'build-' + key.replace(/([A-Z])/g, function($1){return "-"+$1.toLowerCase();});
}
function getArguments() {
return minimist(process.argv.slice(2));
}
function getPlatforms() {
const defaultPlatforms = ['win32', 'win64', 'osx64', 'linux32', 'linux64'];
const platform = getArguments().platform;
if (platform) {
if (defaultPlatforms.indexOf(platform) < 0) {
throw new Error(`Invalid platform "${platform}". Available ones are: ${defaultPlatforms}`)
}
return [platform];
}
return defaultPlatforms;
}
function execSync() {
const cmd = arguments[0];
const args = Array.prototype.slice.call(arguments, 1);
const result = child_process.spawnSync(cmd, args, {stdio: 'inherit'});
if (result.error) {
throw result.error;
}
}
// Define build tasks dynamically based on the sources
// and output variables.
var buildCssTasks = [];
var buildJsTasks = [];
(function() {
// Convers fooBarBaz to foo-bar-baz
for (var k in output) {
(function (key) {
var name = get_task_name(key);
if (name.endsWith('-css')) {
buildCssTasks.push(name);
} else if (name.endsWith('-js')) {
buildJsTasks.push(name);
} else {
throw 'Invalid task name: "' + name + '": must end with -css or -js';
}
gulp.task(name, function() {
return gulp.src(sources[key])
.pipe(concat(output[key]))
.pipe(gulp.dest(outputDir));
});
})(k);
}
})();
gulp.task('build-all-js', gulp.parallel(buildJsTasks))
gulp.task('build-all-css', gulp.parallel(buildCssTasks));
gulp.task('build', gulp.parallel('build-all-css', 'build-all-js'));
gulp.task('clean', function() { return del(['./build/**', './dist/**'], {force: true}); });
// Real work for dist task. Done in another task to call it via
// run-sequence.
gulp.task('dist-build', gulp.series('build', function() {
var distSources = [
'./package.json', // For NW.js
'./manifest.json', // For Chrome app
'./eventPage.js',
'./*.html',
'./tabs/*.html',
'./images/**/*',
'./_locales/**/*',
'./build/*',
'./src/css/font-awesome/webfonts/*',
'./src/css/opensans_webfontkit/*.{eot,svg,ttf,woff,woff2}',
'./resources/*.json',
'./resources/models/*',
'./resources/osd/analogue/*.mcm',
'./resources/motor_order/*.svg',
'./resources/sitl/windows/*',
'./resources/sitl/linux/*'
];
return gulp.src(distSources, { base: '.' })
.pipe(gulp.dest(distDir));
}));
gulp.task('dist', gulp.series('clean', 'dist-build'));
// Create app directories in ./apps
gulp.task('apps', gulp.series('dist', function(done) {
var builder = new NwBuilder({
files: './dist/**/*',
buildDir: appsDir,
platforms: getPlatforms(),
flavor: 'normal',
macIcns: './images/inav.icns',
winIco: './images/inav.ico',
version: get_nw_version(),
zip: false
});
builder.on('log', console.log);
builder.build(function (err) {
if (err) {
console.log("Error building NW apps:" + err);
done();
return;
}
// Package apps as .zip files
done();
});
}));
function get_nw_version() {
return semver.valid(semver.coerce(require('./package.json').dependencies.nw));
}
function get_release_filename_base(platform) {
return 'INAV-Configurator_' + platform;
}
function get_release_filename(platform, ext, addition = '') {
var pkg = require('./package.json');
return get_release_filename_base(platform) + addition + '_' + pkg.version + '.' + ext;
}
function build_win_zip(arch) {
return function build_win_zip_proc(done) {
var pkg = require('./package.json');
// Create ZIP
console.log(`Creating ${arch} ZIP file...`);
var src = path.join(appsDir, pkg.name, arch);
var output = fs.createWriteStream(path.join(appsDir, get_release_filename(arch, 'zip')));
var archive = archiver('zip', {
zlib: { level: 9 }
});
archive.on('warning', function(err) { throw err; });
archive.on('error', function(err) { throw err; });
archive.pipe(output);
archive.directory(src, 'INAV Configurator');
return archive.finalize();
}
}
function build_win_iss(arch) {
return function build_win_iss_proc(done) {
if (!getArguments().installer) {
done();
return null;
}
// Create Installer
console.log(`Creating ${arch} Installer...`);
const innoSetup = require('@quanle94/innosetup');
const APPS_DIR = './apps/';
const pkg = require('./package.json');
// Parameters passed to the installer script
const parameters = [];
// Extra parameters to replace inside the iss file
parameters.push(`/Dversion=${pkg.version}`);
parameters.push(`/DarchName=${arch}`);
parameters.push(`/DarchAllowed=${(arch === 'win32') ? 'x86 x64' : 'x64'}`);
parameters.push(`/DarchInstallIn64bit=${(arch === 'win32') ? '' : 'x64'}`);
parameters.push(`/DsourceFolder=${APPS_DIR}`);
parameters.push(`/DtargetFolder=${APPS_DIR}`);
// Show only errors in console
parameters.push(`/Q`);
// Script file to execute
parameters.push("assets/windows/installer.iss");
innoSetup(parameters, {},
function(error) {
if (error != null) {
console.error(`Installer for platform ${arch} finished with error ${error}`);
} else {
console.log(`Installer for platform ${arch} finished`);
}
done();
});
}
}
gulp.task('release-win32', gulp.series(build_win_zip('win32'), build_win_iss('win32')));
gulp.task('release-win64', gulp.series(build_win_zip('win64'), build_win_iss('win64')));
gulp.task('release-osx64', function(done) {
var pkg = require('./package.json');
var src = path.join(appsDir, pkg.name, 'osx64', pkg.name + '.app');
// Check if we want to sign the .app bundle
if (getArguments().codesign) {
// macapptool can be downloaded from
// https://github.com/fiam/macapptool
//
// Make sure the bundle is well formed
execSync('macapptool', '-v', '1', 'fix', src);
// Sign
const codesignArgs = ['macapptool', '-v', '1', 'sign'];
const codesignIdentity = getArguments()['codesign-identity'];
if (codesignIdentity) {
codesignArgs.push('-i', codesignIdentity);
}
codesignArgs.push('-e', 'entitlements.plist');
codesignArgs.push(src)
execSync.apply(this, codesignArgs);
// Check if the bundle is signed
const codesignCheckArgs = [ 'codesign', '-vvv', '--deep', '--strict', src ];
execSync.apply(this, codesignCheckArgs);
}
// 'old' .zip mode
if (!getArguments().installer) {
const zipFilename = path.join(appsDir, get_release_filename('macOS', 'zip'));
console.log('Creating ZIP file: ' + zipFilename);
var output = fs.createWriteStream(zipFilename);
var archive = archiver('zip', {
zlib: { level: 9 }
});
archive.on('warning', function(err) { throw err; });
archive.on('error', function(err) { throw err; });
archive.pipe(output);
archive.directory(src, 'INAV Configurator.app');
output.on('close', function() {
if (getArguments().notarize) {
console.log('Notarizing ZIP file: ' + zipFilename);
const notarizeArgs = ['xcrun', 'notarytool', 'submit'];
notarizeArgs.push(zipFilename);
const notarizationUsername = getArguments()['notarization-username'];
if (notarizationUsername) {
notarizeArgs.push('--apple-id', notarizationUsername)
} else {
throw new Error('Missing notarization username');
}
const notarizationPassword = getArguments()['notarization-password'];
if (notarizationPassword) {
notarizeArgs.push('--password', notarizationPassword)
} else {
throw new Error('Missing notarization password');
}
const notarizationTeamId = getArguments()['notarization-team-id'];
if (notarizationTeamId) {
notarizeArgs.push('--team-id', notarizationTeamId)
} else {
throw new Error('Missing notarization Team ID');
}
notarizeArgs.push('--wait');
const notarizationWebhook = getArguments()['notarization-webhook'];
if (notarizationWebhook) {
notarizeArgs.push('--webhook', notarizationWebhook);
}
execSync.apply(this, notarizeArgs);
console.log('Stapling ZIP file: ' + zipFilename);
const stapleArgs = ['macapptool', '-v', '1', 'staple'];
stapleArgs.push(zipFilename)
execSync.apply(this, stapleArgs);
}
done();
});
archive.finalize();
}
// 'new' .dmg mode
else {
const appdmg = require('appdmg');
var target = path.join(appsDir, get_release_filename('macOS', 'dmg'));
console.log('Creating DMG file: ' + target);
var basepath = path.join(appsDir, pkg.name, 'osx64');
console.log('Base path: ' + basepath);
if (fs.existsSync(target)) {
fs.unlinkSync(target);
}
var specs = {};
specs["title"] = "INAV Configurator";
specs["contents"] = [
{ "x": 448, "y": 342, "type": "link", "path": "/Applications" },
{ "x": 192, "y": 344, "type": "file", "path": pkg.name + ".app", "name": "INAV Configurator.app" },
];
specs["background"] = path.join(__dirname, 'assets/osx/dmg-background.png');
specs["format"] = "UDZO";
specs["window"] = {
"size": {
"width": 638,
"height": 479,
}
};
const codesignIdentity = getArguments()['codesign-identity'];
if (getArguments().codesign) {
specs['code-sign'] = {
'signing-identity': codesignIdentity,
}
}
const ee = appdmg({
target: target,
basepath: basepath,
specification: specs,
});
ee.on('progress', function(info) {
//console.log(info);
});
ee.on('error', function(err) {
console.log(err);
});
ee.on('finish', function() {
if (getArguments().codesign) {
// Check if the bundle is signed
const codesignCheckArgs = [ 'codesign', '-vvv', '--deep', '--strict', target ];
execSync.apply(this, codesignCheckArgs);
}
if (getArguments().notarize) {
console.log('Notarizing DMG file: ' + target);
const notarizeArgs = ['xcrun', 'notarytool', 'submit'];
notarizeArgs.push(target);
const notarizationUsername = getArguments()['notarization-username'];
if (notarizationUsername) {
notarizeArgs.push('--apple-id', notarizationUsername)
} else {
throw new Error('Missing notarization username');
}
const notarizationPassword = getArguments()['notarization-password'];
if (notarizationPassword) {
notarizeArgs.push('--password', notarizationPassword)
} else {
throw new Error('Missing notarization password');
}
const notarizationTeamId = getArguments()['notarization-team-id'];
if (notarizationTeamId) {
notarizeArgs.push('--team-id', notarizationTeamId)
} else {
throw new Error('Missing notarization Team ID');
}
notarizeArgs.push('--wait');
const notarizationWebhook = getArguments()['notarization-webhook'];
if (notarizationWebhook) {
notarizeArgs.push('--webhook', notarizationWebhook);
}
execSync.apply(this, notarizeArgs);
console.log('Stapling DMG file: ' + target);
const stapleArgs = ['xcrun', 'stapler', 'staple'];
stapleArgs.push(target);
execSync.apply(this, stapleArgs);
console.log('Checking DMG file: ' + target);
const checkArgs = ['spctl', '-vvv', '--assess', '--type', 'install', target];
execSync.apply(this, checkArgs);
}
done();
});
}
});
function post_build(arch, folder) {
return function post_build_linux(done) {
if ((arch === 'linux32') || (arch === 'linux64')) {
const metadata = require('./package.json');
// Copy Ubuntu launcher scripts to destination dir
const launcherDir = path.join(folder, metadata.name, arch);
console.log(`Copy Ubuntu launcher scripts to ${launcherDir}`);
return gulp.src('assets/linux/**')
.pipe(gulp.dest(launcherDir));
}
return done();
}
}
// Create the dir directory, with write permissions
function createDirIfNotExists(dir) {
fs.mkdir(dir, '0775', function(err) {
if (err && err.code !== 'EEXIST') {
throw err;
}
});
}
function release_deb(arch) {
return function release_deb_proc(done) {
if (!getArguments().installer) {
done();
return null;
}
// Check if dpkg-deb exists
if (!commandExistsSync('dpkg-deb')) {
console.warn(`dpkg-deb command not found, not generating deb package for ${arch}`);
done();
return null;
}
const deb = require('gulp-debian');
const LINUX_INSTALL_DIR = '/opt/inav';
const metadata = require('./package.json');
console.log(`Generating deb package for ${arch}`);
return gulp.src([path.join(appsDir, metadata.name, arch, '*')])
.pipe(deb({
package: metadata.name,
version: metadata.version,
section: 'base',
priority: 'optional',
architecture: getLinuxPackageArch('deb', arch),
maintainer: metadata.author,
description: metadata.description,
preinst: [`rm -rf ${LINUX_INSTALL_DIR}/${metadata.name}`],
postinst: [
`chown root:root ${LINUX_INSTALL_DIR}`,
`chown -R root:root ${LINUX_INSTALL_DIR}/${metadata.name}`,
`xdg-desktop-menu install ${LINUX_INSTALL_DIR}/${metadata.name}/${metadata.name}.desktop`,
],
prerm: [`xdg-desktop-menu uninstall ${metadata.name}.desktop`],
depends: ['libatomic1'],
changelog: [],
_target: `${LINUX_INSTALL_DIR}/${metadata.name}`,
_out: appsDir,
_copyright: 'assets/linux/copyright',
_clean: true,
}));
}
}
function post_release_deb(arch) {
return function post_release_linux_deb(done) {
if (!getArguments().installer) {
done();
return null;
}
if ((arch === 'linux32') || (arch === 'linux64')) {
var rename = require("gulp-rename");
const metadata = require('./package.json');
const renameFrom = path.join(appsDir, metadata.name + '_' + metadata.version + '_' + getLinuxPackageArch('.deb', arch) + '.deb');
const renameTo = path.join(appsDir, get_release_filename_base(arch) + '_' + metadata.version + '.deb');
// Rename .deb build to common naming
console.log(`Renaming .deb installer ${renameFrom} to ${renameTo}`);
return gulp.src(renameFrom)
.pipe(rename(renameTo))
.pipe(gulp.dest("."));
}
return done();
}
}
function release_rpm(arch) {
return function release_rpm_proc(done) {
if (!getArguments().installer) {
done();
return null;
}
// Check if rpmbuild exists
if (!commandExistsSync('rpmbuild')) {
console.warn(`rpmbuild command not found, not generating rpm package for ${arch}`);
done();
return;
}
const buildRpm = require('rpm-builder');
const NAME_REGEX = /-/g;
const LINUX_INSTALL_DIR = '/opt/inav';
const metadata = require('./package.json');
console.log(`Generating rpm package for ${arch}`);
// The buildRpm does not generate the folder correctly, manually
createDirIfNotExists(appsDir);
const options = {
name: get_release_filename_base(arch), // metadata.name,
version: metadata.version.replace(NAME_REGEX, '_'), // RPM does not like release candidate versions
buildArch: getLinuxPackageArch('rpm', arch),
vendor: metadata.author,
summary: metadata.description,
license: 'GNU General Public License v3.0',
requires: ['libatomic1'],
prefix: '/opt',
files: [{
cwd: path.join(appsDir, metadata.name, arch),
src: '*',
dest: `${LINUX_INSTALL_DIR}/${metadata.name}`,
}],
postInstallScript: [`xdg-desktop-menu install ${LINUX_INSTALL_DIR}/${metadata.name}/${metadata.name}.desktop`],
preUninstallScript: [`xdg-desktop-menu uninstall ${metadata.name}.desktop`],
tempDir: path.join(appsDir, `tmp-rpm-build-${arch}`),
keepTemp: false,
verbose: false,
rpmDest: appsDir,
execOpts: { maxBuffer: 1024 * 1024 * 16 },
};
buildRpm(options, function(err) {
if (err) {
console.error(`Error generating rpm package: ${err}`);
}
done();
});
}
}
function getLinuxPackageArch(type, arch) {
let packArch;
switch (arch) {
case 'linux32':
packArch = 'i386';
break;
case 'linux64':
if (type === 'rpm') {
packArch = 'x86_64';
} else {
packArch = 'amd64';
}
break;
default:
console.error(`Package error, arch: ${arch}`);
process.exit(1);
break;
}
return packArch;
}
function releaseLinux(bits) {
return function() {
console.log(`Generating zip package for linux${bits}`);
var dirname = 'linux' + bits;
var pkg = require('./package.json');
var src = path.join(appsDir, pkg.name, dirname);
var output = fs.createWriteStream(path.join(appsDir, get_release_filename(dirname, 'tar.gz')));
var archive = archiver('tar', {
zlib: { level: 9 },
gzip: true
});
archive.on('warning', function(err) { throw err; });
archive.on('error', function(err) { throw err; });
archive.pipe(output);
archive.directory(src, 'INAV Configurator');
return archive.finalize();
}
}
gulp.task('release-linux32', gulp.series(releaseLinux(32), post_build('linux32', appsDir), release_deb('linux32'), post_release_deb('linux32')));
gulp.task('release-linux64', gulp.series(releaseLinux(64), post_build('linux64', appsDir), release_deb('linux64'), post_release_deb('linux64'), release_rpm('linux64')));
// Create distributable .zip files in ./apps
gulp.task('release', gulp.series('apps', getPlatforms().map(function(v) { return 'release-' + v; })));
gulp.task('watch', function () {
for(var k in output) {
gulp.watch(sources[k], gulp.series(get_task_name(k)));
}
});
gulp.task('default', gulp.series('build'));

View file

@ -5,9 +5,11 @@
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link type="text/css" rel="stylesheet" href="./src/css/styles.css" media="all" /> <link type="text/css" rel="stylesheet" href="./src/css/styles.css" media="all" />
<script type="text/javascript">require('./js/configurator_main.js');</script> <script type="text/javascript">require('./js/configurator_main.js');</script>
<!-- TODO: Update to newer Versions and use proper modules (require) -->
<script type="text/javascript" src="./js/libraries/three/three.min.js"></script> <script type="text/javascript" src="./js/libraries/three/three.min.js"></script>
<script type="text/javascript" src="./js/libraries/three/OrbitControls.js"></script>
<script type="text/javascript" src="./js/libraries/three/GLTFLoader.js"></script> <script type="text/javascript" src="./js/libraries/three/GLTFLoader.js"></script>
<title></title> <title>INAV Configurator</title>
</head> </head>
<body> <body>

View file

@ -4,13 +4,18 @@
* Uses: https://github.com/yuku/jquery-textcomplete * Uses: https://github.com/yuku/jquery-textcomplete
* Check out the docs at https://github.com/yuku/jquery-textcomplete/tree/v1/doc * Check out the docs at https://github.com/yuku/jquery-textcomplete/tree/v1/doc
*/ */
const FC = require('./fc')
const CONFIGURATOR = require('./data_storage');
const timeout = require('./timeouts');
const CliAutoComplete = { const CliAutoComplete = {
configEnabled: false, configEnabled: false,
builder: { state: 'reset', numFails: 0 }, builder: { state: 'reset', numFails: 0 },
}; };
CliAutoComplete.isEnabled = function() { CliAutoComplete.isEnabled = function() {
return this.isBuilding() || (this.configEnabled && CONFIG.flightControllerIdentifier === "INAV" && this.builder.state !== 'fail'); return this.isBuilding() || (this.configEnabled && FC.CONFIG.flightControllerIdentifier === "INAV" && this.builder.state !== 'fail');
}; };
CliAutoComplete.isBuilding = function() { CliAutoComplete.isBuilding = function() {
@ -67,7 +72,7 @@ CliAutoComplete._builderWatchdogTouch = function() {
this._builderWatchdogStop(); this._builderWatchdogStop();
helper.timeout.add('autocomplete_builder_watchdog', function() { timeout.add('autocomplete_builder_watchdog', function() {
if (self.builder.numFails) { if (self.builder.numFails) {
self.builder.numFails++; self.builder.numFails++;
self.builder.state = 'fail'; self.builder.state = 'fail';
@ -82,7 +87,7 @@ CliAutoComplete._builderWatchdogTouch = function() {
}; };
CliAutoComplete._builderWatchdogStop = function() { CliAutoComplete._builderWatchdogStop = function() {
helper.timeout.remove('autocomplete_builder_watchdog'); timeout.remove('autocomplete_builder_watchdog');
}; };
CliAutoComplete.builderStart = function() { CliAutoComplete.builderStart = function() {

View file

@ -1,5 +1,11 @@
'use strict'; 'use strict';
const semver = require('semver');
const { GUI } = require('./gui');
const jBox = require('./libraries/jBox/jBox.min.js');
const i18n = require('./localization');
var appUpdater = appUpdater || {}; var appUpdater = appUpdater || {};
appUpdater.checkRelease = function (currVersion) { appUpdater.checkRelease = function (currVersion) {
@ -34,3 +40,5 @@ appUpdater.checkRelease = function (currVersion) {
modalStart.close(); modalStart.close();
}); });
}; };
module.exports = appUpdater;

View file

@ -1,7 +1,9 @@
window.$ = window.jQuery = require('jquery'), window.$ = window.jQuery = require('jquery'),
require('jquery-ui-dist/jquery-ui'), require('jquery-ui-dist/jquery-ui'),
require('jquery-textcomplete'), require('jquery-textcomplete'),
require('./libraries/jquery.flightindicators.js'); require('./libraries/jquery.flightindicators.js'),
require('./libraries/jquery.nouislider.all.min.js'),
require('./libraries/jquery.ba-throttle-debounce.js');
const { app } = require('@electron/remote'); const { app } = require('@electron/remote');
const d3 = require('./libraries/d3.min.js'); const d3 = require('./libraries/d3.min.js');
@ -16,9 +18,13 @@ const { PLATFORM } = require('./model.js')
const i18n = require('./localization'); const i18n = require('./localization');
const SerialBackend = require('./serial_backend'); const SerialBackend = require('./serial_backend');
const MSP = require('./msp'); const MSP = require('./msp');
const MSPCodes = require('./../js/msp/MSPCodes');
const mspHelper = require('./msp/MSPHelper.js'); const mspHelper = require('./msp/MSPHelper.js');
const update = require('./globalUpdates.js'); const update = require('./globalUpdates.js');
const appUpdater = require('./appUpdater.js');
const CliAutoComplete = require('./CliAutoComplete.js');
const { SITLProcess } = require('./sitl');
;
process.on('uncaughtException', function (error) { process.on('uncaughtException', function (error) {
if (process.env.NODE_ENV !== 'development') { if (process.env.NODE_ENV !== 'development') {
GUI.log(i18n.getMessage('unexpectedError', error)); GUI.log(i18n.getMessage('unexpectedError', error));
@ -33,7 +39,6 @@ process.on('uncaughtException', function (error) {
// Set how the units render on the configurator only // Set how the units render on the configurator only
$(function() { $(function() {
i18n.init( () => { i18n.init( () => {
i18n.localize(); i18n.localize();
@ -66,6 +71,12 @@ $(function() {
return useEzTune; return useEzTune;
}; };
GUI.updateActivatedTab = function() {
var activeTab = $('#tabs > ul li.active');
activeTab.removeClass('active');
$('a', activeTab).trigger('click');
}
globalSettings.unitType = store.get('unit_type', UnitType.none); globalSettings.unitType = store.get('unit_type', UnitType.none);
globalSettings.mapProviderType = store.get('map_provider_type', 'osm'); globalSettings.mapProviderType = store.get('map_provider_type', 'osm');
globalSettings.mapApiKey = store.get('map_api_key', ''); globalSettings.mapApiKey = store.get('map_api_key', '');
@ -74,10 +85,10 @@ $(function() {
globalSettings.showProfileParameters = store.get('show_profile_parameters', 1); globalSettings.showProfileParameters = store.get('show_profile_parameters', 1);
updateProfilesHighlightColours(); updateProfilesHighlightColours();
if (store.get('cli_autocomplete', true)) { var cliAutocomplete = store.get('cli_autocomplete', true);
globalSettings.cliAutocomplete = true; globalSettings.cliAutocomplete = cliAutocomplete;
//CliAutoComplete.setEnabled(true); CliAutoComplete.setEnabled(cliAutocomplete);
};
// Resets the OSD units used by the unit coversion when the FC is disconnected. // Resets the OSD units used by the unit coversion when the FC is disconnected.
if (!CONFIGURATOR.connectionValid) { if (!CONFIGURATOR.connectionValid) {
@ -97,8 +108,8 @@ $(function() {
$("#showlog").trigger('click'); $("#showlog").trigger('click');
} }
if (store.get('update_notify', true)) { 34 if (store.get('update_notify', true)) {
//appUpdater.checkRelease(app.getVersion()); appUpdater.checkRelease(app.getVersion());
} }
// log library versions in console to make version tracking easier // log library versions in console to make version tracking easier

View file

@ -77,7 +77,7 @@ class ConnectionSerial extends Connection {
if (error) { if (error) {
result = 1; result = 1;
sent = 0; sent = 0;
console.log("Serial wrire error: " + error) console.log("Serial write error: " + error)
} }
if (callback) { if (callback) {
callback({ callback({

View file

@ -66,8 +66,8 @@ class ConnectionTcp extends Connection {
}); });
this._socket.on('error', (error) => { this._socket.on('error', (error) => {
GUI.log("TCP error: " + error); GUI.log(error);
console.log("TCP error: " + error); console.log(error);
if (this._socket) { if (this._socket) {
this.abort(); this.abort();

View file

@ -1,9 +1,15 @@
/*global mspHelper,$,GUI,MSP,chrome*/
'use strict'; 'use strict';
const { GUI } = require('./../js/gui');
const FC = require('./fc.js');
const MSP = require('./msp');
const MSPCodes = require('./../js/msp/MSPCodes');
const mspHelper = require('./msp/MSPHelper'); const mspHelper = require('./msp/MSPHelper');
const MSPChainerClass = require('./msp/MSPchainer.js');
const features = require('./feature_framework'); const features = require('./feature_framework');
const { mixer } = require('./model') const { mixer } = require('./model');
const jBox = require('./libraries/jBox/jBox.min.js');
const i18n = require('./localization.js');
var savingDefaultsModal; var savingDefaultsModal;
@ -997,18 +1003,18 @@ var defaultsDialog = (function () {
if (selectedDefaultPreset.mixerToApply) { if (selectedDefaultPreset.mixerToApply) {
let currentMixerPreset = mixer.getById(selectedDefaultPreset.mixerToApply); let currentMixerPreset = mixer.getById(selectedDefaultPreset.mixerToApply);
mixer.loadServoRules(currentMixerPreset); mixer.loadServoRules(FC, currentMixerPreset);
mixer.loadMotorRules(currentMixerPreset); mixer.loadMotorRules(FC, currentMixerPreset);
MIXER_CONFIG.platformType = currentMixerPreset.platform; FC.MIXER_CONFIG.platformType = currentMixerPreset.platform;
MIXER_CONFIG.appliedMixerPreset = selectedDefaultPreset.mixerToApply; FC.MIXER_CONFIG.appliedMixerPreset = selectedDefaultPreset.mixerToApply;
MIXER_CONFIG.motorStopOnLow = (currentMixerPreset.motorStopOnLow === true) ? true : false; FC.MIXER_CONFIG.motorStopOnLow = (currentMixerPreset.motorStopOnLow === true) ? true : false;
MIXER_CONFIG.hasFlaps = (currentMixerPreset.hasFlaps === true) ? true : false; FC.MIXER_CONFIG.hasFlaps = (currentMixerPreset.hasFlaps === true) ? true : false;
SERVO_RULES.cleanup(); FC.SERVO_RULES.cleanup();
SERVO_RULES.inflate(); FC.SERVO_RULES.inflate();
MOTOR_RULES.cleanup(); FC.MOTOR_RULES.cleanup();
MOTOR_RULES.inflate(); FC.MOTOR_RULES.inflate();
chain = chain.concat([ chain = chain.concat([
mspHelper.saveMixerConfig, mspHelper.saveMixerConfig,

View file

@ -10,10 +10,12 @@ const ProgrammingPidStatus = require('./programmingPidStatus');
const WaypointCollection = require('./waypointCollection'); const WaypointCollection = require('./waypointCollection');
const OutputMappingCollection = require('./outputMapping'); const OutputMappingCollection = require('./outputMapping');
const SafehomeCollection = require('./safehomeCollection'); const SafehomeCollection = require('./safehomeCollection');
const FwApproachCollection = require('./fwApproachCollection.js')
const { PLATFORM } = require('./model.js') const { PLATFORM } = require('./model.js')
const VTX = require('./vtx'); const VTX = require('./vtx');
const BitHelper = require('./bitHelper'); const BitHelper = require('./bitHelper');
var FC = { var FC = {
// define all the global variables that are uses to hold FC state // define all the global variables that are uses to hold FC state
CONFIG: null, CONFIG: null,
@ -584,9 +586,9 @@ var FC = {
}; };
FW_APPROACH = new FwApproachCollection(); this.FW_APPROACH = new FwApproachCollection();
OSD_CUSTOM_ELEMENTS = { this.OSD_CUSTOM_ELEMENTS = {
settings: {customElementsCount: 0, customElementTextSize: 0}, settings: {customElementsCount: 0, customElementTextSize: 0},
items: [], items: [],
}; };
@ -1363,7 +1365,7 @@ var FC = {
4: { 4: {
name: "Logic Condition", name: "Logic Condition",
type: "range", type: "range",
range: [0, (LOGIC_CONDITIONS.getMaxLogicConditionCount()-1)], range: [0, (this.LOGIC_CONDITIONS.getMaxLogicConditionCount()-1)],
default: 0 default: 0
}, },
5: { 5: {

View file

@ -1,4 +1,3 @@
/*global mspHelper,FEATURES,bit_clear,bit_set*/
'use strict'; 'use strict';
/* /*

View file

@ -1,4 +1,3 @@
/*global $*/
'use strict'; 'use strict';
const ApproachDirection = Object.freeze({ const ApproachDirection = Object.freeze({
@ -105,3 +104,5 @@ let FwApproach = function (number, approachAltAsl = 0, landAltAsl = 0, approachD
return self; return self;
}; };
module.exports = { ApproachDirection, FwApproach };

View file

@ -1,5 +1,7 @@
'use strict'; 'use strict';
const BitHelper = require('./bitHelper');
let FwApproachCollection = function () { let FwApproachCollection = function () {
let self = {}, let self = {},
@ -66,19 +68,19 @@ let FwApproachCollection = function () {
let fwApproach = data[fwApproachId]; let fwApproach = data[fwApproachId];
if (fwApproachId < self.fwApproachCount()) { if (fwApproachId < self.fwApproachCount()) {
buffer.push(fwApproach.getNumber()); // sbufReadU8(src); // number buffer.push(fwApproach.getNumber()); // sbufReadU8(src); // number
buffer.push(specificByte(fwApproach.getApproachAltAsl(), 0)); buffer.push(BitHelper.specificByte(fwApproach.getApproachAltAsl(), 0));
buffer.push(specificByte(fwApproach.getApproachAltAsl(), 1)); buffer.push(BitHelper.specificByte(fwApproach.getApproachAltAsl(), 1));
buffer.push(specificByte(fwApproach.getApproachAltAsl(), 2)); buffer.push(BitHelper.specificByte(fwApproach.getApproachAltAsl(), 2));
buffer.push(specificByte(fwApproach.getApproachAltAsl(), 3)); buffer.push(BitHelper.specificByte(fwApproach.getApproachAltAsl(), 3));
buffer.push(specificByte(fwApproach.getLandAltAsl(), 0)); buffer.push(BitHelper.specificByte(fwApproach.getLandAltAsl(), 0));
buffer.push(specificByte(fwApproach.getLandAltAsl(), 1)); buffer.push(BitHelper.specificByte(fwApproach.getLandAltAsl(), 1));
buffer.push(specificByte(fwApproach.getLandAltAsl(), 2)); buffer.push(BitHelper.specificByte(fwApproach.getLandAltAsl(), 2));
buffer.push(specificByte(fwApproach.getLandAltAsl(), 3)); buffer.push(BitHelper.specificByte(fwApproach.getLandAltAsl(), 3));
buffer.push(fwApproach.getApproachDirection()); buffer.push(fwApproach.getApproachDirection());
buffer.push(specificByte(fwApproach.getLandHeading1(), 0)); buffer.push(BitHelper.specificByte(fwApproach.getLandHeading1(), 0));
buffer.push(specificByte(fwApproach.getLandHeading1(), 1)); buffer.push(BitHelper.specificByte(fwApproach.getLandHeading1(), 1));
buffer.push(specificByte(fwApproach.getLandHeading2(), 0)); buffer.push(BitHelper.specificByte(fwApproach.getLandHeading2(), 0));
buffer.push(specificByte(fwApproach.getLandHeading2(), 1)); buffer.push(BitHelper.specificByte(fwApproach.getLandHeading2(), 1));
buffer.push(fwApproach.getIsSeaLevelRef()); buffer.push(fwApproach.getIsSeaLevelRef());
} else { } else {
buffer = Array(15).fill(0); buffer = Array(15).fill(0);
@ -90,3 +92,5 @@ let FwApproachCollection = function () {
return self; return self;
}; };
module.exports = FwApproachCollection;

View file

@ -3,7 +3,6 @@
const CONFIGURATOR = require('./data_storage'); const CONFIGURATOR = require('./data_storage');
const FC = require('./fc'); const FC = require('./fc');
const { globalSettings } = require('./globalSettings'); const { globalSettings } = require('./globalSettings');
const mspHelper = require('./msp/MSPHelper.js');
const i18n = require('./localization'); const i18n = require('./localization');
var update = { var update = {

View file

@ -1,8 +1,14 @@
'use strict'; 'use strict';
var helper = helper || {}; const ol = require('openlayers');
helper.groundstation = (function () { const { GUI } = require('./gui');
const ltmDecoder = require('./ltmDecoder');
const interval = require('./intervals');
const { globalSettings } = require('./globalSettings');
const i18n = require('./localization');
const groundstation = (function () {
let publicScope = {}, let publicScope = {},
privateScope = {}; privateScope = {};
@ -37,14 +43,15 @@ helper.groundstation = (function () {
return; return;
} }
helper.interval.add('gsUpdateGui', privateScope.updateGui, 200); interval.add('gsUpdateGui', privateScope.updateGui, 200);
privateScope.$viewport = $viewport; privateScope.$viewport = $viewport;
privateScope.$viewport.find(".tab_container").hide(); privateScope.$viewport.find(".tab_container").hide();
privateScope.$viewport.find('#content').hide(); privateScope.$viewport.find('#content').hide();
privateScope.$viewport.find('#status-bar').hide(); privateScope.$viewport.find('#status-bar').hide();
privateScope.$viewport.find('#connectbutton a.connect_state').text(chrome.i18n.getMessage('disconnect')).addClass('active'); privateScope.$viewport.find('#connectbutton a.connect_state').text(i18n.getMessage('disconnect'));
privateScope.$viewport.find('#connectbutton a.connect').addClass('active');
privateScope.$gsViewport = $viewport.find('#view-groundstation'); privateScope.$gsViewport = $viewport.find('#view-groundstation');
privateScope.$gsViewport.show(); privateScope.$gsViewport.show();
@ -53,7 +60,7 @@ helper.groundstation = (function () {
setTimeout(privateScope.initMap, 100); setTimeout(privateScope.initMap, 100);
privateScope.activated = true; privateScope.activated = true;
GUI.log(chrome.i18n.getMessage('gsActivated')); GUI.log(i18n.getMessage('gsActivated'));
} }
privateScope.initMap = function () { privateScope.initMap = function () {
@ -98,7 +105,7 @@ helper.groundstation = (function () {
return; return;
} }
helper.interval.remove('gsUpdateGui'); interval.remove('gsUpdateGui');
if (privateScope.$viewport !== null) { if (privateScope.$viewport !== null) {
privateScope.$viewport.find(".tab_container").show(); privateScope.$viewport.find(".tab_container").show();
@ -111,12 +118,12 @@ helper.groundstation = (function () {
} }
privateScope.activated = false; privateScope.activated = false;
GUI.log(chrome.i18n.getMessage('gsDeactivated')); GUI.log(i18n.getMessage('gsDeactivated'));
} }
privateScope.updateGui = function () { privateScope.updateGui = function () {
let telemetry = helper.ltmDecoder.get(); let telemetry = ltmDecoder.get();
if (telemetry.gpsFix && telemetry.gpsFix > 1) { if (telemetry.gpsFix && telemetry.gpsFix > 1) {
@ -191,4 +198,6 @@ helper.groundstation = (function () {
}; };
return publicScope; return publicScope;
})(); })();
module.exports = groundstation;

View file

@ -6,6 +6,7 @@ const MSP = require('./msp');
const FC = require('./fc'); const FC = require('./fc');
const interval = require('./intervals'); const interval = require('./intervals');
const mspBalancedInterval = require('./msp_balanced_interval'); const mspBalancedInterval = require('./msp_balanced_interval');
const { scaleRangeInt } = require('./helpers');
const i18n = require('./localization'); const i18n = require('./localization');
var TABS = {}; // filled by individual tab js file var TABS = {}; // filled by individual tab js file
@ -275,7 +276,7 @@ GUI_control.prototype.updateProfileChange = function(refresh) {
GUI.log(i18n.getMessage('loadedMixerProfile', [FC.CONFIG.mixer_profile + 1])); GUI.log(i18n.getMessage('loadedMixerProfile', [FC.CONFIG.mixer_profile + 1]));
GUI.log(i18n.getMessage('pidTuning_LoadedProfile', [FC.CONFIG.profile + 1])); GUI.log(i18n.getMessage('pidTuning_LoadedProfile', [FC.CONFIG.profile + 1]));
GUI.log(i18n.getMessage('loadedBatteryProfile', [FC.CONFIG.battery_profile + 1])); GUI.log(i18n.getMessage('loadedBatteryProfile', [FC.CONFIG.battery_profile + 1]));
updateActivatedTab(); GUI.updateActivatedTab();
} }
}; };

View file

@ -1,4 +1,3 @@
/*global $*/
'use strict'; 'use strict';
@ -102,3 +101,5 @@ function calculate_new_cooridatnes(coord, bearing, distance)
lon: rad2Deg(lonNew), lon: rad2Deg(lonNew),
} }
} }
module.exports = { constrain, zeroPad, generateFilename, scaleRangeInt, distanceOnLine, wrap_360, rad2Deg, calculate_new_cooridatnes }

View file

@ -10,7 +10,7 @@ const i18nextXHRBackend = require('i18next-xhr-backend');
const Store = require('electron-store'); const Store = require('electron-store');
const store = new Store(); const store = new Store();
const availableLanguages = ['en', 'de']; const availableLanguages = ['en'];
const i18n = {}; const i18n = {};

View file

@ -220,7 +220,7 @@ let LogicCondition = function (enabled, activatorId, operation, operandAType, op
if (self.getEnabled()) { if (self.getEnabled()) {
GUI.renderLogicConditionSelect( GUI.renderLogicConditionSelect(
$e, $e,
LOGIC_CONDITIONS, FC.LOGIC_CONDITIONS,
self.getActivatorId, self.getActivatorId,
self.onActivatorChange, self.onActivatorChange,
true, true,

View file

@ -46,8 +46,6 @@ var LogicConditionsCollection = function () {
self.get()[k].render(k, $table); self.get()[k].render(k, $table);
} }
} }
GUI.switchery();
}; };
self.onSave = function () { self.onSave = function () {

View file

@ -1,8 +1,6 @@
'use strict'; 'use strict';
var helper = helper || {}; const ltmDecoder = (function () {
helper.ltmDecoder = (function () {
let TELEMETRY = { let TELEMETRY = {
//A frame //A frame
@ -257,4 +255,6 @@ helper.ltmDecoder = (function () {
}; };
return publicScope; return publicScope;
})(); })();
module.exports = ltmDecoder;

View file

@ -21,7 +21,7 @@ let bluetoothDeviceChooser = null;
let btDeviceList = null; let btDeviceList = null;
let selectBluetoothCallback = null; let selectBluetoothCallback = null;
// In Eletrcon the bluetooth device chooser didn't exist, so we have to build our own // In Electron the bluetooth device chooser didn't exist, so we have to build our own
function createDeviceChooser() { function createDeviceChooser() {
bluetoothDeviceChooser = new BrowserWindow({ bluetoothDeviceChooser = new BrowserWindow({
parent: mainWindow, parent: mainWindow,
@ -69,7 +69,6 @@ app.on('ready', () => {
webPreferences: { webPreferences: {
nodeIntegration: true, nodeIntegration: true,
contextIsolation: false, contextIsolation: false,
webSecurity: false
}, },
}); });
@ -124,7 +123,7 @@ app.on('ready', () => {
if (details.deviceType === 'usb' && details.origin === 'file://') { if (details.deviceType === 'usb' && details.origin === 'file://') {
return true; return true;
} }
}) });
mainWindow.webContents.setWindowOpenHandler(({ url }) => { mainWindow.webContents.setWindowOpenHandler(({ url }) => {
return { return {
@ -140,7 +139,6 @@ app.on('ready', () => {
require("@electron/remote/main").enable(mainWindow.webContents); require("@electron/remote/main").enable(mainWindow.webContents);
mainWindow.removeMenu(); mainWindow.removeMenu();
mainWindow.setMinimumSize(800, 600); mainWindow.setMinimumSize(800, 600);
mainWindow.loadFile('./index.html'); mainWindow.loadFile('./index.html');
mainWindowState.manage(mainWindow); mainWindowState.manage(mainWindow);

View file

@ -787,13 +787,13 @@ const platformList = [
return retVal; return retVal;
}; };
publicScope.loadServoRules = function (mixer) { publicScope.loadServoRules = function (FC, mixer) {
SERVO_RULES.flush(); FC.SERVO_RULES.flush();
for (const i in mixer.servoMixer) { for (const i in mixer.servoMixer) {
if (mixer.servoMixer.hasOwnProperty(i)) { if (mixer.servoMixer.hasOwnProperty(i)) {
const r = mixer.servoMixer[i]; const r = mixer.servoMixer[i];
SERVO_RULES.put( FC.SERVO_RULES.put(
new ServoMixRule( new ServoMixRule(
r.getTarget(), r.getTarget(),
r.getInput(), r.getInput(),
@ -805,13 +805,13 @@ const platformList = [
} }
} }
publicScope.loadMotorRules = function (mixer) { publicScope.loadMotorRules = function (FC, mixer) {
MOTOR_RULES.flush(); FC.MOTOR_RULES.flush();
for (const i in mixer.motorMixer) { for (const i in mixer.motorMixer) {
if (mixer.motorMixer.hasOwnProperty(i)) { if (mixer.motorMixer.hasOwnProperty(i)) {
const r = mixer.motorMixer[i]; const r = mixer.motorMixer[i];
MOTOR_RULES.put( FC.MOTOR_RULES.put(
new MotorMixRule( new MotorMixRule(
r.getThrottle(), r.getThrottle(),
r.getRoll(), r.getRoll(),

View file

@ -1,6 +1,6 @@
'use strict'; 'use strict';
const { constrain } = require('./helpers') const { constrain } = require('./helpers')
var MotorMixRule = function (throttle, roll, pitch, yaw) { var MotorMixRule = function (throttle, roll, pitch, yaw) {

View file

@ -1,6 +1,7 @@
/*global $, MotorMixRule*/
'use strict'; 'use strict';
const MotorMixRule = require('./motorMixRule');
var MotorMixerRuleCollection = function () { var MotorMixerRuleCollection = function () {
let self = {}, let self = {},

View file

@ -86,6 +86,17 @@ var MSP = {
lastFrameReceivedMs: 0, lastFrameReceivedMs: 0,
processData: null,
init() {
mspQueue.setPutCallback(this.putCallback);
mspQueue.setremoveCallback(this.removeCallback);
},
setProcessData(cb) {
this.processData = cb;
},
read: function (readInfo) { read: function (readInfo) {
var data = new Uint8Array(readInfo.data); var data = new Uint8Array(readInfo.data);
@ -243,7 +254,7 @@ var MSP = {
_dispatch_message(expected_checksum) { _dispatch_message(expected_checksum) {
if (this.message_checksum == expected_checksum) { if (this.message_checksum == expected_checksum) {
// message received, process // message received, process
mspHelper.processData(this); this.processData(this);
this.lastFrameReceivedMs = Date.now(); this.lastFrameReceivedMs = Date.now();
} else { } else {
console.log('code: ' + this.code + ' - crc failed'); console.log('code: ' + this.code + ' - crc failed');
@ -396,8 +407,4 @@ var MSP = {
} }
}; };
MSP.SDCARD_STATE_NOT_PRESENT = 0; module.exports = MSP;
MSP.SDCARD_STATE_FATAL = 1;
MSP.SDCARD_STATE_CARD_INIT = 2;
MSP.SDCARD_STATE_FS_INIT = 3;
MSP.SDCARD_STATE_READY = 4;

View file

@ -1,4 +1,3 @@
/*global $, SERVO_DATA, PID_names, ADJUSTMENT_RANGES, RXFAIL_CONFIG, SERVO_CONFIG,CONFIG*/
'use strict'; 'use strict';
const semver = require('semver'); const semver = require('semver');
@ -8,11 +7,17 @@ const { GUI } = require('./../gui');
const MSP = require('./../msp'); const MSP = require('./../msp');
const MSPCodes = require('./MSPCodes'); const MSPCodes = require('./MSPCodes');
const FC = require('./../fc'); const FC = require('./../fc');
const VTX = require('./../vtx');
const mspQueue = require('./../serial_queue'); const mspQueue = require('./../serial_queue');
const ServoMixRule = require('./../servoMixRule'); const ServoMixRule = require('./../servoMixRule');
const MotorMixRule = require('./../motorMixRule'); const MotorMixRule = require('./../motorMixRule');
const LogicCondition = require('./../logicCondition'); const LogicCondition = require('./../logicCondition');
const BitHelper = require('../bitHelper'); const BitHelper = require('../bitHelper');
const serialPortHelper = require('./../serialPortHelper');
const ProgrammingPid = require('./../programmingPid');
const Safehome = require('./../safehome');
const { FwApproach } = require('./../fwApproach');
const Waypoint = require('./../waypoint');
var mspHelper = (function () { var mspHelper = (function () {
var self = {}; var self = {};
@ -836,7 +841,7 @@ var mspHelper = (function () {
var serialPort = { var serialPort = {
identifier: data.getUint8(offset), identifier: data.getUint8(offset),
functions: helper.serialPortHelper.maskToFunctions(data.getUint32(offset + 1, true)), functions: serialPortHelper.maskToFunctions(data.getUint32(offset + 1, true)),
msp_baudrate: BAUD_RATES[data.getUint8(offset + 5)], msp_baudrate: BAUD_RATES[data.getUint8(offset + 5)],
sensors_baudrate: BAUD_RATES[data.getUint8(offset + 6)], sensors_baudrate: BAUD_RATES[data.getUint8(offset + 6)],
telemetry_baudrate: BAUD_RATES[data.getUint8(offset + 7)], telemetry_baudrate: BAUD_RATES[data.getUint8(offset + 7)],
@ -1530,19 +1535,19 @@ var mspHelper = (function () {
case MSPCodes.MSP2_INAV_TEMPERATURES: case MSPCodes.MSP2_INAV_TEMPERATURES:
for (let i = 0; i < 8; ++i) { for (let i = 0; i < 8; ++i) {
temp_decidegrees = data.getInt16(i * 2, true); let temp_decidegrees = data.getInt16(i * 2, true);
FC.SENSOR_DATA.temperature[i] = temp_decidegrees / 10; // °C FC.SENSOR_DATA.temperature[i] = temp_decidegrees / 10; // °C
} }
break; break;
case MSPCodes.MSP2_INAV_SAFEHOME: case MSPCodes.MSP2_INAV_SAFEHOME:
FC.SAFEHOMES.put(new Safehome( var safeHome = new Safehome(
data.getUint8(0), data.getUint8(0),
data.getUint8(1), data.getUint8(1),
data.getInt32(2, true), data.getInt32(2, true),
data.getInt32(6, true), data.getInt32(6, true),
); );
if (safehome.getEnabled()) { if (safeHome.getEnabled()) {
SAFEHOMES.put(safehome); FC.SAFEHOMES.put(safeHome);
} }
break; break;
@ -1551,7 +1556,7 @@ var mspHelper = (function () {
break; break;
case MSPCodes.MSP2_INAV_FW_APPROACH: case MSPCodes.MSP2_INAV_FW_APPROACH:
FW_APPROACH.put(new FwApproach( FC.FW_APPROACH.put(new FwApproach(
data.getUint8(0), data.getUint8(0),
data.getInt32(1, true), data.getInt32(1, true),
data.getInt32(5, true), data.getInt32(5, true),
@ -1596,27 +1601,27 @@ var mspHelper = (function () {
break; break;
case MSPCodes.MSP2_INAV_CUSTOM_OSD_ELEMENTS: case MSPCodes.MSP2_INAV_CUSTOM_OSD_ELEMENTS:
OSD_CUSTOM_ELEMENTS.items = []; FC.OSD_CUSTOM_ELEMENTS .items = [];
var index = 0; var index = 0;
if(data.byteLength == 0){ if(data.byteLength == 0){
OSD_CUSTOM_ELEMENTS.settings.customElementsCount = 0; FC.OSD_CUSTOM_ELEMENTS .settings.customElementsCount = 0;
OSD_CUSTOM_ELEMENTS.settings.customElementTextSize = 0; FC.OSD_CUSTOM_ELEMENTS .settings.customElementTextSize = 0;
return; return;
} }
OSD_CUSTOM_ELEMENTS.settings.customElementsCount = data.getUint8(index++); FC.OSD_CUSTOM_ELEMENTS .settings.customElementsCount = data.getUint8(index++);
OSD_CUSTOM_ELEMENTS.settings.customElementTextSize = data.getUint8(index++); FC.OSD_CUSTOM_ELEMENTS .settings.customElementTextSize = data.getUint8(index++);
for (i = 0; i < OSD_CUSTOM_ELEMENTS.settings.customElementsCount; i++){ for (i = 0; i < FC.OSD_CUSTOM_ELEMENTS .settings.customElementsCount; i++){
var customElement = { var customElement = {
customElementItems: [], customElementItems: [],
customElementVisibility: {type: 0, value: 0}, customElementVisibility: {type: 0, value: 0},
customElementText: [], customElementText: [],
}; };
for (let ii = 0; ii < OSD_CUSTOM_ELEMENTS.settings.customElementsCount; ii++){ for (let ii = 0; ii < FC.OSD_CUSTOM_ELEMENTS .settings.customElementsCount; ii++){
var customElementPart = {type: 0, value: 0,}; var customElementPart = {type: 0, value: 0,};
customElementPart.type = data.getUint8(index++); customElementPart.type = data.getUint8(index++);
customElementPart.value = data.getUint16(index, true); customElementPart.value = data.getUint16(index, true);
@ -1628,10 +1633,10 @@ var mspHelper = (function () {
customElement.customElementVisibility.value = data.getUint16(index, true); customElement.customElementVisibility.value = data.getUint16(index, true);
index += 2; index += 2;
for (let ii = 0; ii < OSD_CUSTOM_ELEMENTS.settings.customElementTextSize; ii++){ for (let ii = 0; ii < FC.OSD_CUSTOM_ELEMENTS .settings.customElementTextSize; ii++){
var char = data.getUint8(index++); var char = data.getUint8(index++);
if(char === 0){ if(char === 0){
index += (OSD_CUSTOM_ELEMENTS.settings.customElementTextSize - 1) - ii; index += (FC.OSD_CUSTOM_ELEMENTS .settings.customElementTextSize - 1) - ii;
break; break;
} }
customElement.customElementText[ii] = char; customElement.customElementText[ii] = char;
@ -1639,7 +1644,7 @@ var mspHelper = (function () {
customElement.customElementText = String.fromCharCode(...customElement.customElementText); customElement.customElementText = String.fromCharCode(...customElement.customElementText);
OSD_CUSTOM_ELEMENTS.items.push(customElement) FC.OSD_CUSTOM_ELEMENTS .items.push(customElement)
} }
break; break;
@ -1687,10 +1692,10 @@ var mspHelper = (function () {
switch (code) { switch (code) {
case MSPCodes.MSP_SET_FEATURE: case MSPCodes.MSP_SET_FEATURE:
buffer.push(BitHelper.specificByte(FC.FEATURESS, 0)); buffer.push(BitHelper.specificByte(FC.FEATURES, 0));
buffer.push(BitHelper.specificByte(FC.FEATURESS, 1)); buffer.push(BitHelper.specificByte(FC.FEATURES, 1));
buffer.push(BitHelper.specificByte(FC.FEATURESS, 2)); buffer.push(BitHelper.specificByte(FC.FEATURES, 2));
buffer.push(BitHelper.specificByte(FC.FEATURESS, 3)); buffer.push(BitHelper.specificByte(FC.FEATURES, 3));
break; break;
case MSPCodes.MSP_SET_BOARD_ALIGNMENT: case MSPCodes.MSP_SET_BOARD_ALIGNMENT:
@ -1926,7 +1931,7 @@ var mspHelper = (function () {
buffer.push(serialPort.identifier); buffer.push(serialPort.identifier);
var functionMask = mspHelper.SERIAL_PORT_FUNCTIONSToMask(serialPort.functions); var functionMask = serialPortHelper.functionsToMask(serialPort.functions);
buffer.push(BitHelper.specificByte(functionMask, 0)); buffer.push(BitHelper.specificByte(functionMask, 0));
buffer.push(BitHelper.specificByte(functionMask, 1)); buffer.push(BitHelper.specificByte(functionMask, 1));
buffer.push(BitHelper.specificByte(functionMask, 2)); buffer.push(BitHelper.specificByte(functionMask, 2));
@ -2874,7 +2879,7 @@ var mspHelper = (function () {
MSP.send_message(MSPCodes.MSP2_INAV_TIMER_OUTPUT_MODE, false, false, callback); MSP.send_message(MSPCodes.MSP2_INAV_TIMER_OUTPUT_MODE, false, false, callback);
} }
self.sendTimerOutputModes = function(callback) { self.sendTimerOutputModes = function(onCompleteCallback) {
var nextFunction = send_next_output_mode; var nextFunction = send_next_output_mode;
var idIndex = 0; var idIndex = 0;
@ -3131,13 +3136,13 @@ var mspHelper = (function () {
}; };
self.loadFwApproach = function (callback) { self.loadFwApproach = function (callback) {
FW_APPROACH.flush(); FC.FW_APPROACH.flush();
let id = 0; let id = 0;
MSP.send_message(MSPCodes.MSP2_INAV_FW_APPROACH, [id], false, nextFwApproach); MSP.send_message(MSPCodes.MSP2_INAV_FW_APPROACH, [id], false, nextFwApproach);
function nextFwApproach() { function nextFwApproach() {
id++; id++;
if (id < FW_APPROACH.getMaxFwApproachCount() - 1) { if (id < FC.FW_APPROACH.getMaxFwApproachCount() - 1) {
MSP.send_message(MSPCodes.MSP2_INAV_FW_APPROACH, [id], false, nextFwApproach); MSP.send_message(MSPCodes.MSP2_INAV_FW_APPROACH, [id], false, nextFwApproach);
} }
else { else {
@ -3148,15 +3153,15 @@ var mspHelper = (function () {
self.saveFwApproach = function (callback) { self.saveFwApproach = function (callback) {
let id = 0; let id = 0;
MSP.send_message(MSPCodes.MSP2_INAV_SET_FW_APPROACH, FW_APPROACH.extractBuffer(id), false, nextFwApproach); MSP.send_message(MSPCodes.MSP2_INAV_SET_FW_APPROACH, FC.FW_APPROACH.extractBuffer(id), false, nextFwApproach);
function nextFwApproach() { function nextFwApproach() {
id++; id++;
if (id < FW_APPROACH.getMaxFwApproachCount() - 1) { if (id < FC.FW_APPROACH.getMaxFwApproachCount() - 1) {
MSP.send_message(MSPCodes.MSP2_INAV_SET_FW_APPROACH, FW_APPROACH.extractBuffer(id), false, nextFwApproach); MSP.send_message(MSPCodes.MSP2_INAV_SET_FW_APPROACH, FC.FW_APPROACH.extractBuffer(id), false, nextFwApproach);
} }
else { else {
MSP.send_message(MSPCodes.MSP2_INAV_SET_FW_APPROACH, FW_APPROACH.extractBuffer(id), false, callback); MSP.send_message(MSPCodes.MSP2_INAV_SET_FW_APPROACH, FC.FW_APPROACH.extractBuffer(id), false, callback);
} }
}; };
}; };
@ -3329,7 +3334,7 @@ var mspHelper = (function () {
return MSP.promise(MSPCodes.MSPV2_SET_SETTING, data).then(callback); return MSP.promise(MSPCodes.MSPV2_SET_SETTING, data).then(callback);
}).catch(error => { }).catch(error => {
console.log("Invalid setting: " + name); console.log("Invalid setting: " + name);
return new Promise(callback); return Promise.resolve().then(callback);
}); });
}; };

36
js/mwnp.js Normal file
View file

@ -0,0 +1,36 @@
'use strict'
// MultiWii NAV Protocol
const MWNP = {};
MWNP.WPTYPE = {
WAYPOINT: 1,
POSHOLD_UNLIM: 2,
POSHOLD_TIME: 3,
RTH: 4,
SET_POI: 5,
JUMP: 6,
SET_HEAD: 7,
LAND: 8
};
MWNP.P3 = {
ALT_TYPE: 0, // Altitude (alt) : Relative (to home altitude) (0) or Absolute (AMSL) (1).
USER_ACTION_1: 1, // WP Action 1
USER_ACTION_2: 2, // WP Action 2
USER_ACTION_3: 3, // WP Action 3
USER_ACTION_4: 4, // WP Action 4
}
MWNP.WPTYPE.REV = swap(MWNP.WPTYPE);
// Reverse WayPoint type dictionary
function swap(dict) {
let rev_dict = {};
for (let key in dict) {
rev_dict[dict[key]] = key;
}
return rev_dict;
}
module.exports = MWNP;

View file

@ -1,4 +1,3 @@
/*global bit_check*/
'use strict'; 'use strict';
var OutputMappingCollection = function () { var OutputMappingCollection = function () {

View file

@ -1,9 +1,11 @@
'use strict'; 'use strict';
const FC = require('./fc');
// return true if user has choose a special peripheral // return true if user has choose a special peripheral
function isPeripheralSelected(peripheralName) { function isPeripheralSelected(peripheralName) {
for (var portIndex = 0; portIndex < SERIAL_CONFIG.ports.length; portIndex++) { for (var portIndex = 0; portIndex < FC.SERIAL_CONFIG.ports.length; portIndex++) {
var serialPort = SERIAL_CONFIG.ports[portIndex]; var serialPort = FC.SERIAL_CONFIG.ports[portIndex];
if (serialPort.functions.indexOf(peripheralName) >= 0) { if (serialPort.functions.indexOf(peripheralName) >= 0) {
return true; return true;
} }
@ -36,4 +38,4 @@ function adjustBoxNameIfPeripheralWithModeID(modeId, defaultName) {
return defaultName; return defaultName;
} }
module.exports = { isPeripheralSelected, adjustBoxNameIfPeripheralWithModeID }; module.exports = adjustBoxNameIfPeripheralWithModeID ;

View file

@ -1,6 +1,8 @@
/*global $,FC*/
'use strict'; 'use strict';
const FC = require('./fc');
const { GUI } = require('./gui');
let ProgrammingPid = function (enabled, setpointType, setpointValue, measurementType, measurementValue, gainP, gainI, gainD, gainFF) { let ProgrammingPid = function (enabled, setpointType, setpointValue, measurementType, measurementValue, gainP, gainI, gainD, gainFF) {
let self = {}; let self = {};
let $row; let $row;

View file

@ -40,8 +40,6 @@ var ProgrammingPidCollection = function () {
self.get()[k].render(k, $table); self.get()[k].render(k, $table);
} }
} }
GUI.switchery();
}; };
self.update = function(statuses) { self.update = function(statuses) {

View file

@ -1,4 +1,3 @@
/*global $*/
'use strict'; 'use strict';
var Safehome = function (number, enabled, lat, lon) { var Safehome = function (number, enabled, lat, lon) {

View file

@ -1,5 +1,7 @@
'use strict'; 'use strict';
const BitHelper = require('./bitHelper');
var SafehomeCollection = function () { var SafehomeCollection = function () {
let self = {}, let self = {},
@ -67,14 +69,14 @@ var SafehomeCollection = function () {
if (safehomeId < self.safehomeCount()) { if (safehomeId < self.safehomeCount()) {
buffer.push(safehome.getNumber()); // sbufReadU8(src); // number buffer.push(safehome.getNumber()); // sbufReadU8(src); // number
buffer.push(1); buffer.push(1);
buffer.push(specificByte(safehome.getLat(), 0)); // sbufReadU32(src); // lat buffer.push(BitHelper.specificByte(safehome.getLat(), 0)); // sbufReadU32(src); // lat
buffer.push(specificByte(safehome.getLat(), 1)); buffer.push(BitHelper.specificByte(safehome.getLat(), 1));
buffer.push(specificByte(safehome.getLat(), 2)); buffer.push(BitHelper.specificByte(safehome.getLat(), 2));
buffer.push(specificByte(safehome.getLat(), 3)); buffer.push(BitHelper.specificByte(safehome.getLat(), 3));
buffer.push(specificByte(safehome.getLon(), 0)); // sbufReadU32(src); // lon buffer.push(BitHelper.specificByte(safehome.getLon(), 0)); // sbufReadU32(src); // lon
buffer.push(specificByte(safehome.getLon(), 1)); buffer.push(BitHelper.specificByte(safehome.getLon(), 1));
buffer.push(specificByte(safehome.getLon(), 2)); buffer.push(BitHelper.specificByte(safehome.getLon(), 2));
buffer.push(specificByte(safehome.getLon(), 3)); buffer.push(BitHelper.specificByte(safehome.getLon(), 3));
} else { } else {
buffer = Array(10).fill(0); buffer = Array(10).fill(0);
buffer[0] = safehomeId; buffer[0] = safehomeId;

View file

@ -1,8 +1,10 @@
'use strict'; 'use strict';
var helper = helper || {}; const FC = require('./fc');
const i18n = require('./localization');
const bitHelper = require('./bitHelper');
helper.serialPortHelper = (function () { const serialPortHelper = (function () {
let publicScope = {}, let publicScope = {},
privateScope = {}; privateScope = {};
@ -209,7 +211,7 @@ helper.serialPortHelper = (function () {
} }
for (var i = 0; i < privateScope.rules.length; i++) { for (var i = 0; i < privateScope.rules.length; i++) {
privateScope.rules[i].displayName = chrome.i18n.getMessage('portsFunction_' + privateScope.rules[i].name); privateScope.rules[i].displayName = i18n.getMessage('portsFunction_' + privateScope.rules[i].name);
} }
privateScope.namesGenerated = true; privateScope.namesGenerated = true;
@ -242,7 +244,7 @@ helper.serialPortHelper = (function () {
let key = functions[index]; let key = functions[index];
let bitIndex = privateScope.functionIDs[key]; let bitIndex = privateScope.functionIDs[key];
if (bitIndex >= 0) { if (bitIndex >= 0) {
mask = bit_set(mask, bitIndex); mask = bitHelper.bit_set(mask, bitIndex);
} }
} }
return mask; return mask;
@ -260,7 +262,7 @@ helper.serialPortHelper = (function () {
for (let index = 0; index < keys.length; index++) { for (let index = 0; index < keys.length; index++) {
let key = keys[index]; let key = keys[index];
let bit = privateScope.functionIDs[key]; let bit = privateScope.functionIDs[key];
if (bit_check(mask, bit)) { if (bitHelper.bit_check(mask, bit)) {
functions.push(key); functions.push(key);
} }
} }
@ -274,8 +276,8 @@ helper.serialPortHelper = (function () {
publicScope.getPortIdentifiersForFunction = function (functionName) { publicScope.getPortIdentifiersForFunction = function (functionName) {
let identifiers = []; let identifiers = [];
for (let index = 0; index < SERIAL_CONFIG.ports.length; index++) { for (let index = 0; index < FC.SERIAL_CONFIG.ports.length; index++) {
let config = SERIAL_CONFIG.ports[index]; let config = FC.SERIAL_CONFIG.ports[index];
if (config.functions.indexOf(functionName) != -1) { if (config.functions.indexOf(functionName) != -1) {
identifiers.push(config.identifier); identifiers.push(config.identifier);
} }
@ -288,8 +290,8 @@ helper.serialPortHelper = (function () {
let list = []; let list = [];
for (let index = 0; index < SERIAL_CONFIG.ports.length; index++) { for (let index = 0; index < FC.SERIAL_CONFIG.ports.length; index++) {
let config = SERIAL_CONFIG.ports[index]; let config = FC.SERIAL_CONFIG.ports[index];
//exclude USB VCP port //exclude USB VCP port
if (config.identifier == 20) { if (config.identifier == 20) {
@ -310,8 +312,8 @@ helper.serialPortHelper = (function () {
}; };
publicScope.getPortByIdentifier = function (identifier) { publicScope.getPortByIdentifier = function (identifier) {
for (let index = 0; index < SERIAL_CONFIG.ports.length; index++) { for (let index = 0; index < FC.SERIAL_CONFIG.ports.length; index++) {
let config = SERIAL_CONFIG.ports[index]; let config = FC.SERIAL_CONFIG.ports[index];
if (config.identifier == identifier) { if (config.identifier == identifier) {
return config; return config;
} }
@ -320,8 +322,8 @@ helper.serialPortHelper = (function () {
}; };
publicScope.clearByFunction = function (functionName) { publicScope.clearByFunction = function (functionName) {
for (let index = 0; index < SERIAL_CONFIG.ports.length; index++) { for (let index = 0; index < FC.SERIAL_CONFIG.ports.length; index++) {
let config = SERIAL_CONFIG.ports[index]; let config = FC.SERIAL_CONFIG.ports[index];
if (config.functions.indexOf(functionName) != -1) { if (config.functions.indexOf(functionName) != -1) {
config.functions = []; config.functions = [];
} }
@ -348,4 +350,6 @@ helper.serialPortHelper = (function () {
} }
return publicScope; return publicScope;
})(); })();
module.exports = serialPortHelper;

View file

@ -23,8 +23,10 @@ const defaultsDialog = require('./defaults_dialog');
const { SITLProcess } = require('./sitl'); const { SITLProcess } = require('./sitl');
const update = require('./globalUpdates.js'); const update = require('./globalUpdates.js');
const BitHelper = require('./bitHelper.js'); const BitHelper = require('./bitHelper.js');
const BOARD = require('./boards.js') const BOARD = require('./boards.js');
const jBox = require('./libraries/jBox/jBox.min.js') const jBox = require('./libraries/jBox/jBox.min.js');
const groundstation = require('./groundstation.js');
const ltmDecoder = require('./ltmDecoder.js');
var SerialBackend = (function () { var SerialBackend = (function () {
@ -161,8 +163,8 @@ var SerialBackend = (function () {
$('div.connect_controls a.connect').click(function () { $('div.connect_controls a.connect').click(function () {
if (helper.groundstation.isActivated()) { if (groundstation.isActivated()) {
helper.groundstation.deactivate(); groundstation.deactivate();
} }
if (GUI.connect_lock != true) { // GUI control overrides the user control if (GUI.connect_lock != true) { // GUI control overrides the user control
@ -359,31 +361,31 @@ var SerialBackend = (function () {
store.set('last_used_bps', CONFIGURATOR.connection.bitrate); store.set('last_used_bps', CONFIGURATOR.connection.bitrate);
store.set('wireless_mode_enabled', $('#wireless-mode').is(":checked")); store.set('wireless_mode_enabled', $('#wireless-mode').is(":checked"));
CONFIGURATOR.connection.addOnReceiveListener(read_serial); CONFIGURATOR.connection.addOnReceiveListener(publicScope.read_serial);
CONFIGURATOR.connection.addOnReceiveListener(helper.ltmDecoder.read); CONFIGURATOR.connection.addOnReceiveListener(ltmDecoder.read);
// disconnect after 10 seconds with error if we don't get IDENT data // disconnect after 10 seconds with error if we don't get IDENT data
helper.timeout.add('connecting', function () { timeout.add('connecting', function () {
//As we add LTM listener, we need to invalidate connection only when both protocols are not listening! //As we add LTM listener, we need to invalidate connection only when both protocols are not listening!
if (!CONFIGURATOR.connectionValid && !helper.ltmDecoder.isReceiving()) { if (!CONFIGURATOR.connectionValid && !ltmDecoder.isReceiving()) {
GUI.log(chrome.i18n.getMessage('noConfigurationReceived')); GUI.log(i18n.getMessage('noConfigurationReceived'));
mspQueue.flush(); mspQueue.flush();
mspQueue.freeHardLock(); mspQueue.freeHardLock();
mspQueue.freeSoftLock(); mspQueue.freeSoftLock();
CONFIGURATOR.connection.emptyOutputBuffer(); CONFIGURATOR.connection.emptyOutputBuffer();
$('div.connect_controls a').click(); // disconnect $('div.connect_controls a').click(); // disconnect
} }
}, 10000); }, 10000);
//Add a timer that every 1s will check if LTM stream is receiving data and display alert if so //Add a timer that every 1s will check if LTM stream is receiving data and display alert if so
helper.interval.add('ltm-connection-check', function () { interval.add('ltm-connection-check', function () {
if (helper.ltmDecoder.isReceiving()) { if (ltmDecoder.isReceiving()) {
helper.groundstation.activate($('#main-wrapper')); groundstation.activate($('#main-wrapper'));
} }
}, 1000); }, 1000);
FC.resetState(); FC.resetState();
@ -592,7 +594,7 @@ var SerialBackend = (function () {
switch(sensor_code) { switch(sensor_code) {
case 'acc': case 'acc':
case 'gyro': case 'gyro':
return BitHelper.check(sensors_detected, 0); return BitHelper.bit_check(sensors_detected, 0);
case 'baro': case 'baro':
return BitHelper.bit_check(sensors_detected, 1); return BitHelper.bit_check(sensors_detected, 1);
case 'mag': case 'mag':

View file

@ -1,4 +1,3 @@
/*global $*/
'use strict'; 'use strict';
var ServoMixRule = function (target, input, rate, speed, condition) { var ServoMixRule = function (target, input, rate, speed, condition) {

View file

@ -1,6 +1,7 @@
/*global ServoMixRule*/
'use strict'; 'use strict';
const ServoMixRule = require('./servoMixRule');
var ServoMixerRuleCollection = function () { var ServoMixerRuleCollection = function () {
let self = {}, let self = {},

View file

@ -6,6 +6,7 @@ const mspHelper = require('./../js/msp/MSPHelper');
const { GUI } = require('./gui'); const { GUI } = require('./gui');
const FC = require('./fc'); const FC = require('./fc');
const { globalSettings, UnitType } = require('./globalSettings'); const { globalSettings, UnitType } = require('./globalSettings');
const i18n = require('./localization');
function padZeros(val, length) { function padZeros(val, length) {
let str = val.toString(); let str = val.toString();

View file

@ -17,7 +17,7 @@
self.init = function ($dom) { self.init = function ($dom) {
$container = $dom; $container = $dom;
$container.find(".subtab__header_label").on('click',(onHeaderClick); $container.find(".subtab__header_label").on('click', onHeaderClick);
}; };
return self; return self;

View file

@ -1,4 +1,3 @@
/*global $*/
'use strict'; 'use strict';
let Waypoint = function (number, action, lat, lon, alt=0, p1=0, p2=0, p3=0, endMission=0, isUsed=true, isAttached=false, attachedId="", multiMissionIdx = 0) { let Waypoint = function (number, action, lat, lon, alt=0, p1=0, p2=0, p3=0, endMission=0, isUsed=true, isAttached=false, attachedId="", multiMissionIdx = 0) {

View file

@ -1,5 +1,9 @@
'use strict'; 'use strict';
const ol = require('openlayers');
const MWNP = require('./mwnp');
const BitHelper = require('./bitHelper');
let WaypointCollection = function () { let WaypointCollection = function () {
@ -255,24 +259,24 @@ let WaypointCollection = function () {
let waypoint = self.getWaypoint(waypointId); let waypoint = self.getWaypoint(waypointId);
buffer.push(waypoint.getNumber()); // sbufReadU8(src); // number buffer.push(waypoint.getNumber()); // sbufReadU8(src); // number
buffer.push(waypoint.getAction()); // sbufReadU8(src); // action buffer.push(waypoint.getAction()); // sbufReadU8(src); // action
buffer.push(specificByte(waypoint.getLat(), 0)); // sbufReadU32(src); // lat buffer.push(BitHelper.specificByte(waypoint.getLat(), 0)); // sbufReadU32(src); // lat
buffer.push(specificByte(waypoint.getLat(), 1)); buffer.push(BitHelper.specificByte(waypoint.getLat(), 1));
buffer.push(specificByte(waypoint.getLat(), 2)); buffer.push(BitHelper.specificByte(waypoint.getLat(), 2));
buffer.push(specificByte(waypoint.getLat(), 3)); buffer.push(BitHelper.specificByte(waypoint.getLat(), 3));
buffer.push(specificByte(waypoint.getLon(), 0)); // sbufReadU32(src); // lon buffer.push(BitHelper.specificByte(waypoint.getLon(), 0)); // sbufReadU32(src); // lon
buffer.push(specificByte(waypoint.getLon(), 1)); buffer.push(BitHelper.specificByte(waypoint.getLon(), 1));
buffer.push(specificByte(waypoint.getLon(), 2)); buffer.push(BitHelper.specificByte(waypoint.getLon(), 2));
buffer.push(specificByte(waypoint.getLon(), 3)); buffer.push(BitHelper.specificByte(waypoint.getLon(), 3));
buffer.push(specificByte(waypoint.getAlt(), 0)); // sbufReadU32(src); // to set altitude (cm) buffer.push(BitHelper.specificByte(waypoint.getAlt(), 0)); // sbufReadU32(src); // to set altitude (cm)
buffer.push(specificByte(waypoint.getAlt(), 1)); buffer.push(BitHelper.specificByte(waypoint.getAlt(), 1));
buffer.push(specificByte(waypoint.getAlt(), 2)); buffer.push(BitHelper.specificByte(waypoint.getAlt(), 2));
buffer.push(specificByte(waypoint.getAlt(), 3)); buffer.push(BitHelper.specificByte(waypoint.getAlt(), 3));
buffer.push(lowByte(waypoint.getP1())); //sbufReadU16(src); // P1 speed or landing buffer.push(BitHelper.lowByte(waypoint.getP1())); //sbufReadU16(src); // P1 speed or landing
buffer.push(highByte(waypoint.getP1())); buffer.push(BitHelper.highByte(waypoint.getP1()));
buffer.push(lowByte(waypoint.getP2())); //sbufReadU16(src); // P2 buffer.push(BitHelper.lowByte(waypoint.getP2())); //sbufReadU16(src); // P2
buffer.push(highByte(waypoint.getP2())); buffer.push(BitHelper.highByte(waypoint.getP2()));
buffer.push(lowByte(waypoint.getP3())); //sbufReadU16(src); // P3 buffer.push(BitHelper.lowByte(waypoint.getP3())); //sbufReadU16(src); // P3
buffer.push(highByte(waypoint.getP3())); buffer.push(BitHelper.highByte(waypoint.getP3()));
buffer.push(waypoint.getEndMission()); //sbufReadU8(src); // future: to set nav flag buffer.push(waypoint.getEndMission()); //sbufReadU8(src); // future: to set nav flag
return buffer; return buffer;

File diff suppressed because it is too large Load diff

2294
main.css

File diff suppressed because it is too large Load diff

1443
package-lock.json generated

File diff suppressed because it is too large Load diff

View file

@ -35,11 +35,11 @@
"marked": "^11.2.0", "marked": "^11.2.0",
"minimist": "^1.2.0", "minimist": "^1.2.0",
"openlayers": "^4.6.5", "openlayers": "^4.6.5",
"plotly": "^1.0.6",
"temp": "^0.8.3", "temp": "^0.8.3",
"xml2js": "^0.4.19", "xml2js": "^0.4.19",
"i18next": "^23.8.3", "i18next": "^23.8.3",
"i18next-xhr-backend": "^3.2.2" "i18next-xhr-backend": "^3.2.2",
"wnumb": "^1.2.0"
}, },
"devDependencies": { "devDependencies": {
"@electron-forge/cli": "^7.2.0", "@electron-forge/cli": "^7.2.0",

View file

@ -1001,7 +1001,7 @@ li.active .ic_mag {
#content { #content {
margin-top: 0; margin-top: 0;
padding: 0; padding: 0;
height: calc(100% - 165px); height: calc(100% - 145px);
/* (port picker 105px, log CLOSED 25px, status bar: 20px + padding) - was: calc(100% - 171px)*/ /* (port picker 105px, log CLOSED 25px, status bar: 20px + padding) - was: calc(100% - 171px)*/
background-color: white; background-color: white;
overflow-x: hidden; overflow-x: hidden;

View file

@ -38,3 +38,4 @@
@import 'tabs/sensors.css'; @import 'tabs/sensors.css';
@import 'tabs/setup.css'; @import 'tabs/setup.css';
@import 'tabs/sitl.css'; @import 'tabs/sitl.css';
@import 'groundstation.css';

View file

@ -1,6 +1,18 @@
/*global $*/
'use strict'; 'use strict';
const path = require('path');
const wNumb = require('wnumb/wNumb')
const mspHelper = require('./../js/msp/MSPHelper');
const MSPCodes = require('./../js/msp/MSPCodes');
const MSP = require('./../js/msp');
const mspQueue = require('./../js/serial_queue');
const { GUI, TABS } = require('./../js/gui');
const FC = require('./../js/fc');
const mspBalancedInterval = require('./../js/msp_balanced_interval');
const i18n = require('./../js/localization');
TABS.adjustments = {}; TABS.adjustments = {};
TABS.adjustments.initialize = function (callback) { TABS.adjustments.initialize = function (callback) {
@ -20,7 +32,7 @@ TABS.adjustments.initialize = function (callback) {
} }
function load_html() { function load_html() {
GUI.load(path.join(__dirname, "tabs/adjustments.html"), process_html); GUI.load(path.join(__dirname, "adjustments.html"), process_html);
} }
MSP.send_message(MSPCodes.MSP_BOXNAMES, false, false, get_adjustment_ranges); MSP.send_message(MSPCodes.MSP_BOXNAMES, false, false, get_adjustment_ranges);
@ -160,11 +172,11 @@ TABS.adjustments.initialize = function (callback) {
function process_html() { function process_html() {
var auxChannelCount = RC.active_channels - 4; var auxChannelCount = FC.RC.active_channels - 4;
var modeTableBodyElement = $('.tab-adjustments .adjustments tbody') var modeTableBodyElement = $('.tab-adjustments .adjustments tbody')
for (var adjustmentIndex = 0; adjustmentIndex < ADJUSTMENT_RANGES.length; adjustmentIndex++) { for (var adjustmentIndex = 0; adjustmentIndex < FC.ADJUSTMENT_RANGES.length; adjustmentIndex++) {
var newAdjustment = addAdjustment(adjustmentIndex, ADJUSTMENT_RANGES[adjustmentIndex], auxChannelCount); var newAdjustment = addAdjustment(adjustmentIndex, FC.ADJUSTMENT_RANGES[adjustmentIndex], auxChannelCount);
modeTableBodyElement.append(newAdjustment); modeTableBodyElement.append(newAdjustment);
} }
@ -175,9 +187,9 @@ TABS.adjustments.initialize = function (callback) {
$('a.save').on('click', function () { $('a.save').on('click', function () {
// update internal data structures based on current UI elements // update internal data structures based on current UI elements
var requiredAdjustmentRangeCount = ADJUSTMENT_RANGES.length; var requiredAdjustmentRangeCount = FC.ADJUSTMENT_RANGES.length;
ADJUSTMENT_RANGES = []; FC.ADJUSTMENT_RANGES = [];
var defaultAdjustmentRange = { var defaultAdjustmentRange = {
slotIndex: 0, slotIndex: 0,
@ -205,14 +217,14 @@ TABS.adjustments.initialize = function (callback) {
adjustmentFunction: parseInt($(this).find('.functionSelection .function').val()), adjustmentFunction: parseInt($(this).find('.functionSelection .function').val()),
auxSwitchChannelIndex: parseInt($(this).find('.functionSwitchChannel .channel').val()) auxSwitchChannelIndex: parseInt($(this).find('.functionSwitchChannel .channel').val())
}; };
ADJUSTMENT_RANGES.push(adjustmentRange); FC.ADJUSTMENT_RANGES.push(adjustmentRange);
} else { } else {
ADJUSTMENT_RANGES.push(defaultAdjustmentRange); FC.ADJUSTMENT_RANGES.push(defaultAdjustmentRange);
} }
}); });
for (var adjustmentRangeIndex = ADJUSTMENT_RANGES.length; adjustmentRangeIndex < requiredAdjustmentRangeCount; adjustmentRangeIndex++) { for (var adjustmentRangeIndex = FC.ADJUSTMENT_RANGES.length; adjustmentRangeIndex < requiredAdjustmentRangeCount; adjustmentRangeIndex++) {
ADJUSTMENT_RANGES.push(defaultAdjustmentRange); FC.ADJUSTMENT_RANGES.push(defaultAdjustmentRange);
} }
// //
@ -249,7 +261,7 @@ TABS.adjustments.initialize = function (callback) {
// data pulling functions used inside interval timer // data pulling functions used inside interval timer
function get_rc_data() { function get_rc_data() {
if (helper.mspQueue.shouldDrop()) { if (mspQueue.shouldDrop()) {
return; return;
} }
@ -257,10 +269,10 @@ TABS.adjustments.initialize = function (callback) {
} }
function update_ui() { function update_ui() {
var auxChannelCount = RC.active_channels - 4; var auxChannelCount = FC.RC.active_channels - 4;
for (var auxChannelIndex = 0; auxChannelIndex < auxChannelCount; auxChannelIndex++) { for (var auxChannelIndex = 0; auxChannelIndex < auxChannelCount; auxChannelIndex++) {
update_marker(auxChannelIndex, RC.channels[auxChannelIndex + 4]); update_marker(auxChannelIndex, FC.RC.channels[auxChannelIndex + 4]);
} }
} }
@ -268,7 +280,7 @@ TABS.adjustments.initialize = function (callback) {
update_ui(); update_ui();
// enable data pulling // enable data pulling
helper.mspBalancedInterval.add('aux_data_pull', 50, 1, get_rc_data); mspBalancedInterval.add('aux_data_pull', 50, 1, get_rc_data);
GUI.content_ready(callback); GUI.content_ready(callback);
} }

View file

@ -1,5 +1,14 @@
'use strict'; 'use strict';
const path = require('path');
const MSPCodes = require('./../js/msp/MSPCodes');
const MSP = require('./../js/msp');
const { GUI, TABS } = require('./../js/gui');
const FC = require('./../js/fc');
const Settings = require('./../js/settings');
const i18n = require('./../js/localization');
TABS.advanced_tuning = {}; TABS.advanced_tuning = {};
TABS.advanced_tuning.initialize = function (callback) { TABS.advanced_tuning.initialize = function (callback) {
@ -11,7 +20,7 @@ TABS.advanced_tuning.initialize = function (callback) {
loadHtml(); loadHtml();
function loadHtml() { function loadHtml() {
GUI.load(path.join(__dirname, "tabs/advanced_tuning.html"), Settings.processHtml(function () { GUI.load(path.join(__dirname, "advanced_tuning.html"), Settings.processHtml(function () {
if (FC.isAirplane()) { if (FC.isAirplane()) {
$('.airplaneTuning').show(); $('.airplaneTuning').show();
@ -35,18 +44,18 @@ TABS.advanced_tuning.initialize = function (callback) {
GUI.simpleBind(); GUI.simpleBind();
i18n.localize();; i18n.localize();;
// Set up required field warnings // Set up required field warnings
$('#launchIdleThr').keyup(function() { $('#launchIdleThr').on('keyup', () => {
TABS.advanced_tuning.checkRequirements_IdleThrottle(); TABS.advanced_tuning.checkRequirements_IdleThrottle();
}); });
$('#launchIdleDelay').keyup(function() { $('#launchIdleDelay').on('keyup', () => {
TABS.advanced_tuning.checkRequirements_IdleThrottle(); TABS.advanced_tuning.checkRequirements_IdleThrottle();
}); });
$('#rthHomeAltitude').keyup(function() { $('#rthHomeAltitude').on('keyup', () => {
TABS.advanced_tuning.checkRequirements_LinearDescent(); TABS.advanced_tuning.checkRequirements_LinearDescent();
}); });

View file

@ -1,5 +1,22 @@
'use strict'; 'use strict';
const path = require('path');
const wNumb = require('wnumb/wNumb')
const Store = require('electron-store');
const store = new Store();
const mspHelper = require('./../js/msp/MSPHelper');
const MSPCodes = require('./../js/msp/MSPCodes');
const MSP = require('./../js/msp');
const mspQueue = require('./../js/serial_queue');
const mspBalancedInterval = require('./../js/msp_balanced_interval');
const { GUI, TABS } = require('./../js/gui');
const FC = require('./../js/fc');
const adjustBoxNameIfPeripheralWithModeID = require('./../js/peripherals');
const i18n = require('./../js/localization');
var ORIG_AUX_CONFIG_IDS = []; var ORIG_AUX_CONFIG_IDS = [];
TABS.auxiliary = {}; TABS.auxiliary = {};
@ -16,7 +33,7 @@ TABS.auxiliary.initialize = function (callback) {
} }
function get_rc_data() { function get_rc_data() {
if (SERIAL_CONFIG.ports.length == 0) { if (FC.SERIAL_CONFIG.ports.length == 0) {
MSP.send_message(MSPCodes.MSP_RC, false, false, get_ports_data); MSP.send_message(MSPCodes.MSP_RC, false, false, get_ports_data);
} else { } else {
MSP.send_message(MSPCodes.MSP_RC, false, false, load_html); MSP.send_message(MSPCodes.MSP_RC, false, false, load_html);
@ -29,7 +46,7 @@ TABS.auxiliary.initialize = function (callback) {
function load_html() { function load_html() {
sort_modes_for_display(); sort_modes_for_display();
GUI.load(path.join(__dirname, "tabs/auxiliary.html"), process_html); GUI.load(path.join(__dirname, "auxiliary.html"), process_html);
} }
MSP.send_message(MSPCodes.MSP_BOXNAMES, false, false, get_mode_ranges); MSP.send_message(MSPCodes.MSP_BOXNAMES, false, false, get_mode_ranges);
@ -53,21 +70,21 @@ TABS.auxiliary.initialize = function (callback) {
var found = false; var found = false;
var sortedID = 0; var sortedID = 0;
for (let i=0; i<AUX_CONFIG.length; i++) { for (let i=0; i<FC.AUX_CONFIG.length; i++) {
tmpAUX_CONFIG[i] = AUX_CONFIG[i]; tmpAUX_CONFIG[i] = FC.AUX_CONFIG[i];
tmpAUX_CONFIG_IDS[i] = AUX_CONFIG_IDS[i]; tmpAUX_CONFIG_IDS[i] = FC.AUX_CONFIG_IDS[i];
} }
AUX_CONFIG = []; FC.AUX_CONFIG = [];
AUX_CONFIG_IDS = []; FC.AUX_CONFIG_IDS = [];
for (let categoryModesIndex in modeSections) { for (let categoryModesIndex in modeSections) {
let categoryModes = modeSections[categoryModesIndex]; let categoryModes = modeSections[categoryModesIndex];
for (let cM=0; cM<categoryModes.length; cM++){ for (let cM=0; cM<categoryModes.length; cM++){
for(let j=0; j<tmpAUX_CONFIG.length; j++) { for(let j=0; j<tmpAUX_CONFIG.length; j++) {
if (categoryModes[cM] === tmpAUX_CONFIG[j]) { if (categoryModes[cM] === tmpAUX_CONFIG[j]) {
AUX_CONFIG[sortedID] = tmpAUX_CONFIG[j]; FC.AUX_CONFIG[sortedID] = tmpAUX_CONFIG[j];
AUX_CONFIG_IDS[sortedID] = tmpAUX_CONFIG_IDS[j]; FC.AUX_CONFIG_IDS[sortedID] = tmpAUX_CONFIG_IDS[j];
ORIG_AUX_CONFIG_IDS[sortedID++] = j; ORIG_AUX_CONFIG_IDS[sortedID++] = j;
break; break;
@ -77,19 +94,19 @@ TABS.auxiliary.initialize = function (callback) {
} }
// There are modes that are missing from the modeSections object. Add them to the end until they are ordered correctly. // There are modes that are missing from the modeSections object. Add them to the end until they are ordered correctly.
if (tmpAUX_CONFIG.length > AUX_CONFIG.length) { if (tmpAUX_CONFIG.length > FC.AUX_CONFIG.length) {
for (let i=0; i<tmpAUX_CONFIG.length; i++) { for (let i=0; i<tmpAUX_CONFIG.length; i++) {
found = false; found = false;
for (let j=0; j<AUX_CONFIG.length; j++) { for (let j=0; j<FC.AUX_CONFIG.length; j++) {
if (tmpAUX_CONFIG[i] === AUX_CONFIG[j]) { if (tmpAUX_CONFIG[i] === FC.AUX_CONFIG[j]) {
found = true; found = true;
break; break;
} }
} }
if (!found) { if (!found) {
AUX_CONFIG[sortedID] = tmpAUX_CONFIG[i]; FC.AUX_CONFIG[sortedID] = tmpAUX_CONFIG[i];
AUX_CONFIG_IDS[sortedID] = tmpAUX_CONFIG_IDS[i]; FC.AUX_CONFIG_IDS[sortedID] = tmpAUX_CONFIG_IDS[i];
ORIG_AUX_CONFIG_IDS[sortedID++] = i; ORIG_AUX_CONFIG_IDS[sortedID++] = i;
} }
} }
@ -108,7 +125,7 @@ TABS.auxiliary.initialize = function (callback) {
function createMode(modeIndex, modeId) { function createMode(modeIndex, modeId) {
var modeTemplate = $('#tab-auxiliary-templates .mode'); var modeTemplate = $('#tab-auxiliary-templates .mode');
var newMode = modeTemplate.clone(); var newMode = modeTemplate.clone();
var modeName = AUX_CONFIG[modeIndex]; var modeName = FC.AUX_CONFIG[modeIndex];
// If the runcam split peripheral is used, then adjust the boxname(BOXCAMERA1, BOXCAMERA2, BOXCAMERA3) // If the runcam split peripheral is used, then adjust the boxname(BOXCAMERA1, BOXCAMERA2, BOXCAMERA3)
// If platform is fixed wing, rename POS HOLD to LOITER // If platform is fixed wing, rename POS HOLD to LOITER
@ -120,7 +137,7 @@ TABS.auxiliary.initialize = function (callback) {
$(newMode).data('index', modeIndex); $(newMode).data('index', modeIndex);
$(newMode).data('id', modeId); $(newMode).data('id', modeId);
$(newMode).data('origId', ORIG_AUX_CONFIG_IDS[modeIndex]); $(newMode).data('origId', ORIG_AUX_CONFIG_IDS[modeIndex]);
$(newMode).data('modeName', AUX_CONFIG[modeIndex]); $(newMode).data('modeName', FC.AUX_CONFIG[modeIndex]);
$(newMode).find('.name').data('modeElement', newMode); $(newMode).find('.name').data('modeElement', newMode);
$(newMode).find('a.addRange').data('modeElement', newMode); $(newMode).find('a.addRange').data('modeElement', newMode);
@ -207,7 +224,7 @@ TABS.auxiliary.initialize = function (callback) {
function process_html() { function process_html() {
var auxChannelCount = RC.active_channels - 4; var auxChannelCount = FC.RC.active_channels - 4;
configureRangeTemplate(auxChannelCount); configureRangeTemplate(auxChannelCount);
@ -215,10 +232,10 @@ TABS.auxiliary.initialize = function (callback) {
let modeSelectionID = ""; let modeSelectionID = "";
let modeSelectionRange = ""; let modeSelectionRange = "";
for (var modeIndex = 0; modeIndex < AUX_CONFIG.length; modeIndex++) { for (var modeIndex = 0; modeIndex < FC.AUX_CONFIG.length; modeIndex++) {
// Get current mode category // Get current mode category
for (modeSelectionRange in modeSections) { for (modeSelectionRange in modeSections) {
if (modeSections[modeSelectionRange].indexOf(AUX_CONFIG[modeIndex]) != -1) { if (modeSections[modeSelectionRange].indexOf(FC.AUX_CONFIG[modeIndex]) != -1) {
break; break;
} }
} }
@ -230,13 +247,13 @@ TABS.auxiliary.initialize = function (callback) {
modeTableBodyElement.append(newSection); modeTableBodyElement.append(newSection);
} }
var modeId = AUX_CONFIG_IDS[modeIndex]; var modeId = FC.AUX_CONFIG_IDS[modeIndex];
var newMode = createMode(modeIndex, modeId); var newMode = createMode(modeIndex, modeId);
modeTableBodyElement.append(newMode); modeTableBodyElement.append(newMode);
// generate ranges from the supplied AUX names and MODE_RANGE data // generate ranges from the supplied AUX names and MODE_RANGE data
for (var modeRangeIndex = 0; modeRangeIndex < MODE_RANGES.length; modeRangeIndex++) { for (var modeRangeIndex = 0; modeRangeIndex < FC.MODE_RANGES.length; modeRangeIndex++) {
var modeRange = MODE_RANGES[modeRangeIndex]; var modeRange = FC.MODE_RANGES[modeRangeIndex];
if (modeRange.id != modeId) { if (modeRange.id != modeId) {
continue; continue;
@ -285,9 +302,9 @@ TABS.auxiliary.initialize = function (callback) {
// update internal data structures based on current UI elements // update internal data structures based on current UI elements
// we must send this many back to the FC - overwrite all of the old ones to be sure. // we must send this many back to the FC - overwrite all of the old ones to be sure.
var requiredModesRangeCount = MODE_RANGES.length; var requiredModesRangeCount = FC.MODE_RANGES.length;
MODE_RANGES = []; FC.MODE_RANGES = [];
var uniqueModes = []; var uniqueModes = [];
@ -308,11 +325,11 @@ TABS.auxiliary.initialize = function (callback) {
uniqueModes.push(modeElement.find('.name').text()); uniqueModes.push(modeElement.find('.name').text());
MODE_RANGES.push(modeRange); FC.MODE_RANGES.push(modeRange);
}); });
}); });
for (var modeRangeIndex = MODE_RANGES.length; modeRangeIndex < requiredModesRangeCount; modeRangeIndex++) { for (var modeRangeIndex = FC.MODE_RANGES.length; modeRangeIndex < requiredModesRangeCount; modeRangeIndex++) {
var defaultModeRange = { var defaultModeRange = {
id: 0, id: 0,
auxChannelIndex: 0, auxChannelIndex: 0,
@ -321,7 +338,7 @@ TABS.auxiliary.initialize = function (callback) {
end: 900 end: 900
} }
}; };
MODE_RANGES.push(defaultModeRange); FC.MODE_RANGES.push(defaultModeRange);
} }
// //
// send data to FC // send data to FC
@ -359,7 +376,7 @@ TABS.auxiliary.initialize = function (callback) {
// data pulling functions used inside interval timer // data pulling functions used inside interval timer
function get_rc_data() { function get_rc_data() {
if (helper.mspQueue.shouldDrop()) { if (mspQueue.shouldDrop()) {
return; return;
} }
@ -371,13 +388,13 @@ TABS.auxiliary.initialize = function (callback) {
let acroEnabled = true; let acroEnabled = true;
let acroFail = ["ANGLE", "HORIZON", "MANUAL", "NAV RTH", "NAV POSHOLD", "NAV CRUISE", "NAV COURSE HOLD", "NAV WP", "GCS NAV"]; let acroFail = ["ANGLE", "HORIZON", "MANUAL", "NAV RTH", "NAV POSHOLD", "NAV CRUISE", "NAV COURSE HOLD", "NAV WP", "GCS NAV"];
var auxChannelCount = RC.active_channels - 4; var auxChannelCount = FC.RC.active_channels - 4;
for (var i = 0; i < (auxChannelCount); i++) { for (var i = 0; i < (auxChannelCount); i++) {
update_marker(i, RC.channels[i + 4]); update_marker(i, FC.RC.channels[i + 4]);
} }
for (var i = 0; i < AUX_CONFIG.length; i++) { for (var i = 0; i < FC.AUX_CONFIG.length; i++) {
var modeElement = $('#mode-' + i); var modeElement = $('#mode-' + i);
let inRange = false; let inRange = false;
@ -432,14 +449,14 @@ TABS.auxiliary.initialize = function (callback) {
} }
let hideUnused = hideUnusedModes && hasUsedMode; let hideUnused = hideUnusedModes && hasUsedMode;
for (let i = 0; i < AUX_CONFIG.length; i++) { for (let i = 0; i < FC.AUX_CONFIG.length; i++) {
let modeElement = $('#mode-' + i); let modeElement = $('#mode-' + i);
if (modeElement.find(' .range').length == 0) { if (modeElement.find(' .range').length == 0) {
modeElement.toggle(!hideUnused); modeElement.toggle(!hideUnused);
} }
} }
auto_select_channel(RC.channels, RC.active_channels, MISC.rssi_channel); auto_select_channel(FC.RC.channels, FC.RC.active_channels, FC.MISC.rssi_channel);
$(".modeSection").each(function() { $(".modeSection").each(function() {
$(this).toggle(!hideUnused); $(this).toggle(!hideUnused);
@ -499,7 +516,7 @@ TABS.auxiliary.initialize = function (callback) {
update_ui(); update_ui();
// enable data pulling // enable data pulling
helper.mspBalancedInterval.add('aux_data_pull', 50, 1, get_rc_data); mspBalancedInterval.add('aux_data_pull', 50, 1, get_rc_data);
$(".tab-auxiliary .acroEnabled").width($("#mode-0 .info").width()); $(".tab-auxiliary .acroEnabled").width($("#mode-0 .info").width());

View file

@ -1,4 +1,3 @@
/*global chrome */
'use strict'; 'use strict';
const path = require('path'); const path = require('path');
@ -9,7 +8,10 @@ const MSPCodes = require('./../js/msp/MSPCodes');
const MSP = require('./../js/msp'); const MSP = require('./../js/msp');
const { GUI, TABS } = require('./../js/gui'); const { GUI, TABS } = require('./../js/gui');
const FC = require('./../js/fc'); const FC = require('./../js/fc');
const timeout = require('./../js/timeouts');
const interval = require('./../js/intervals.js');
const i18n = require('./../js/localization'); const i18n = require('./../js/localization');
const jBox = require('./../js/libraries/jBox/jBox.min.js');
TABS.calibration = {}; TABS.calibration = {};
@ -174,7 +176,7 @@ TABS.calibration.initialize = function (callback) {
GUI.log(i18n.getMessage('initialSetupAccelCalibStarted')); GUI.log(i18n.getMessage('initialSetupAccelCalibStarted'));
}); });
helper.timeout.add('acc_calibration_timeout', function () { timeout.add('acc_calibration_timeout', function () {
$button.removeClass('disabled'); $button.removeClass('disabled');
modalProcessing.close(); modalProcessing.close();
@ -255,7 +257,7 @@ TABS.calibration.initialize = function (callback) {
}).open(); }).open();
var countdown = 30; var countdown = 30;
helper.interval.add('compass_calibration_interval', function () { interval.add('compass_calibration_interval', function () {
countdown--; countdown--;
if (countdown === 0) { if (countdown === 0) {
setTimeout(function () { setTimeout(function () {
@ -265,7 +267,7 @@ TABS.calibration.initialize = function (callback) {
GUI.log(i18n.getMessage('initialSetupMagCalibEnded')); GUI.log(i18n.getMessage('initialSetupMagCalibEnded'));
MSP.send_message(MSPCodes.MSP_CALIBRATION_DATA, false, false, updateSensorData); MSP.send_message(MSPCodes.MSP_CALIBRATION_DATA, false, false, updateSensorData);
helper.interval.remove('compass_calibration_interval'); interval.remove('compass_calibration_interval');
//Cleanup //Cleanup
//delete modalProcessing; //delete modalProcessing;
@ -297,7 +299,7 @@ TABS.calibration.initialize = function (callback) {
}).open(); }).open();
var countdown = 30; var countdown = 30;
helper.interval.add('opflow_calibration_interval', function () { interval.add('opflow_calibration_interval', function () {
countdown--; countdown--;
$('#modal-opflow-countdown').text(countdown); $('#modal-opflow-countdown').text(countdown);
if (countdown === 0) { if (countdown === 0) {
@ -306,7 +308,7 @@ TABS.calibration.initialize = function (callback) {
modalProcessing.close(); modalProcessing.close();
GUI.log(i18n.getMessage('initialSetupOpflowCalibEnded')); GUI.log(i18n.getMessage('initialSetupOpflowCalibEnded'));
MSP.send_message(MSPCodes.MSP_CALIBRATION_DATA, false, false, updateSensorData); MSP.send_message(MSPCodes.MSP_CALIBRATION_DATA, false, false, updateSensorData);
helper.interval.remove('opflow_calibration_interval'); interval.remove('opflow_calibration_interval');
} }
}, 1000); }, 1000);
}); });
@ -321,7 +323,7 @@ TABS.calibration.initialize = function (callback) {
}); });
// translate to user-selected language // translate to user-selected language
i18n.localize();; i18n.localize();
setupCalibrationButton(); setupCalibrationButton();
$('#calibrate-start-button').on('click', actionCalibrateButton); $('#calibrate-start-button').on('click', actionCalibrateButton);

View file

@ -1,7 +1,19 @@
'use strict'; 'use strict';
const path = require('path');
const { dialog } = require("@electron/remote");
const MSP = require('./../js/msp');
const mspQueue = require('./../js/serial_queue');
const { GUI, TABS } = require('./../js/gui');
const CONFIGURATOR = require('./../js/data_storage');
var timeout = require('./../js/timeouts');
const i18n = require('./../js/localization');
const { globalSettings } = require('./../js/globalSettings');
const CliAutoComplete = require('./../js/CliAutoComplete');
const { ConnectionType } = require('./../js/connection/connection');
const jBox = require('./../js/libraries/jBox/jBox.min.js');
/*global chrome,GUI,TABS,$*/
TABS.cli = { TABS.cli = {
lineDelayMs: 50, lineDelayMs: 50,
profileSwitchDelayMs: 100, profileSwitchDelayMs: 100,
@ -81,7 +93,7 @@ TABS.cli.initialize = function (callback) {
} }
// Flush MSP queue as well as all MSP registered callbacks // Flush MSP queue as well as all MSP registered callbacks
helper.mspQueue.flush(); mspQueue.flush();
MSP.callbacks_cleanup(); MSP.callbacks_cleanup();
self.outputHistory = ""; self.outputHistory = "";
@ -103,7 +115,7 @@ TABS.cli.initialize = function (callback) {
return outputArray.reduce((p, line, index) => return outputArray.reduce((p, line, index) =>
p.then((delay) => p.then((delay) =>
new Promise((resolve) => { new Promise((resolve) => {
helper.timeout.add('CLI_send_slowly', () => { timeout.add('CLI_send_slowly', () => {
let processingDelay = TABS.cli.lineDelayMs; let processingDelay = TABS.cli.lineDelayMs;
if (line.toLowerCase().startsWith('profile')) { if (line.toLowerCase().startsWith('profile')) {
processingDelay = TABS.cli.profileSwitchDelayMs; processingDelay = TABS.cli.profileSwitchDelayMs;
@ -121,7 +133,7 @@ TABS.cli.initialize = function (callback) {
); );
} }
GUI.load(path.join(__dirname, "tabs/cli.html"), function () { GUI.load(path.join(__dirname, "cli.html"), function () {
// translate to user-selected language // translate to user-selected language
i18n.localize(); i18n.localize();
@ -235,7 +247,7 @@ TABS.cli.initialize = function (callback) {
isolateScroll: false, isolateScroll: false,
title: i18n.getMessage("cliConfirmSnippetDialogTitle"), title: i18n.getMessage("cliConfirmSnippetDialogTitle"),
content: $('#snippetpreviewcontent'), content: $('#snippetpreviewcontent'),
onCreated: () => $("#snippetpreviewcontent a.confirm").on('click', function () executeSnippet()), onCreated: () => $("#snippetpreviewcontent a.confirm").on('click', executeSnippet),
}); });
} }
previewArea.val(result); previewArea.val(result);
@ -260,7 +272,7 @@ TABS.cli.initialize = function (callback) {
// Tab key detection must be on keydown, // Tab key detection must be on keydown,
// `keypress`/`keyup` happens too late, as `textarea` will have already lost focus. // `keypress`/`keyup` happens too late, as `textarea` will have already lost focus.
textarea.keydown(function (event) { textarea.on('keydown', function (event) {
const tabKeyCode = 9; const tabKeyCode = 9;
if (event.which == tabKeyCode) { if (event.which == tabKeyCode) {
// prevent default tabbing behaviour // prevent default tabbing behaviour
@ -281,7 +293,7 @@ TABS.cli.initialize = function (callback) {
} }
}); });
textarea.keypress(function (event) { textarea.on('keypress', function (event) {
const enterKeyCode = 13; const enterKeyCode = 13;
if (event.which == enterKeyCode) { if (event.which == enterKeyCode) {
event.preventDefault(); // prevent the adding of new line event.preventDefault(); // prevent the adding of new line
@ -304,7 +316,7 @@ TABS.cli.initialize = function (callback) {
} }
}); });
textarea.keyup(function (event) { textarea.on('keyup', function (event) {
var keyUp = {38: true}, var keyUp = {38: true},
keyDown = {40: true}; keyDown = {40: true};
@ -324,7 +336,7 @@ TABS.cli.initialize = function (callback) {
// give input element user focus // give input element user focus
textarea.focus(); textarea.focus();
helper.timeout.add('enter_cli', function enter_cli() { timeout.add('enter_cli', function enter_cli() {
// Enter CLI mode // Enter CLI mode
var bufferOut = new ArrayBuffer(1); var bufferOut = new ArrayBuffer(1);
var bufView = new Uint8Array(bufferOut); var bufView = new Uint8Array(bufferOut);
@ -341,7 +353,7 @@ TABS.cli.initialize = function (callback) {
if (CONFIGURATOR.connection.type == ConnectionType.BLE) { if (CONFIGURATOR.connection.type == ConnectionType.BLE) {
let delay = CONFIGURATOR.connection.deviceDescription.delay; let delay = CONFIGURATOR.connection.deviceDescription.delay;
if (delay > 0) { if (delay > 0) {
helper.timeout.add('cli_delay', () => { timeout.add('cli_delay', () => {
self.send(getCliCommand("cli_delay " + delay + '\n', TABS.cli.cliBuffer)); self.send(getCliCommand("cli_delay " + delay + '\n', TABS.cli.cliBuffer));
self.send(getCliCommand('# ' + i18n.getMessage('connectionBleCliEnter') + '\n', TABS.cli.cliBuffer)); self.send(getCliCommand('# ' + i18n.getMessage('connectionBleCliEnter') + '\n', TABS.cli.cliBuffer));
}, 400); }, 400);
@ -523,7 +535,7 @@ TABS.cli.cleanup = function (callback) {
// (another approach is however much more complicated): // (another approach is however much more complicated):
// we can setup an interval asking for data lets say every 200ms, when data arrives, callback will be triggered and tab switched // we can setup an interval asking for data lets say every 200ms, when data arrives, callback will be triggered and tab switched
// we could probably implement this someday // we could probably implement this someday
helper.timeout.add('waiting_for_bootup', function waiting_for_bootup() { timeout.add('waiting_for_bootup', function waiting_for_bootup() {
if (callback) callback(); if (callback) callback();
}, 1000); // if we dont allow enough time to reboot, CRC of "first" command sent will fail, keep an eye for this one }, 1000); // if we dont allow enough time to reboot, CRC of "first" command sent will fail, keep an eye for this one
CONFIGURATOR.cliActive = false; CONFIGURATOR.cliActive = false;

View file

@ -1,6 +1,19 @@
/*global chrome,GUI,FC_CONFIG,$,mspHelper,googleAnalytics,ADVANCED_CONFIG,VTX_CONFIG,CONFIG,MSPChainerClass,BOARD_ALIGNMENT,TABS,MISC*/
'use strict'; 'use strict';
const path = require('path');
const MSPChainerClass = require('./../js/msp/MSPchainer');
const mspHelper = require('./../js/msp/MSPHelper');
const MSPCodes = require('./../js/msp/MSPCodes');
const MSP = require('./../js/msp');
const { GUI, TABS } = require('./../js/gui');
const FC = require('./../js/fc');
const interval = require('./../js/intervals');
const VTX = require('./../js/vtx');
const i18n = require('./../js/localization');
const Settings = require('./../js/settings');
const features = require('./../js/feature_framework');
TABS.configuration = {}; TABS.configuration = {};
TABS.configuration.initialize = function (callback, scrollPosition) { TABS.configuration.initialize = function (callback, scrollPosition) {
@ -61,7 +74,7 @@ TABS.configuration.initialize = function (callback, scrollPosition) {
} }
function load_html() { function load_html() {
GUI.load(path.join(__dirname, "tabs/configuration.html"), Settings.processHtml(process_html)); GUI.load(path.join(__dirname, "configuration.html"), Settings.processHtml(process_html));
} }
function process_html() { function process_html() {
@ -69,20 +82,20 @@ TABS.configuration.initialize = function (callback, scrollPosition) {
let i; let i;
// generate features // generate features
var features = FC.getFeatures(); var fcFeatures = FC.getFeatures();
var features_e = $('.features'); var features_e = $('.features');
for (let i = 0; i < features.length; i++) { for (let i = 0; i < fcFeatures.length; i++) {
var row_e, var row_e,
tips = [], tips = [],
feature_tip_html = ''; feature_tip_html = '';
if (features[i].showNameInTip) { if (fcFeatures[i].showNameInTip) {
tips.push(i18n.getMessage("manualEnablingTemplate").replace("{name}", features[i].name)); tips.push(i18n.getMessage("manualEnablingTemplate").replace("{name}", fcFeatures[i].name));
} }
if (features[i].haveTip) { if (fcFeatures[i].haveTip) {
tips.push(i18n.getMessage("feature" + features[i].name + "Tip")); tips.push(i18n.getMessage("feature" + fcFeatures[i].name + "Tip"));
} }
if (tips.length > 0) { if (tips.length > 0) {
@ -90,35 +103,35 @@ TABS.configuration.initialize = function (callback, scrollPosition) {
} }
row_e = $('<div class="checkbox">' + row_e = $('<div class="checkbox">' +
'<input type="checkbox" data-bit="' + features[i].bit + '" class="feature toggle" name="' + features[i].name + '" title="' + features[i].name + '"' + '<input type="checkbox" data-bit="' + fcFeatures[i].bit + '" class="feature toggle" name="' + fcFeatures[i].name + '" title="' + fcFeatures[i].name + '"' +
' id="feature-' + features[i].bit + '" ' + ' id="feature-' + fcFeatures[i].bit + '" ' +
'>' + '>' +
'<label for="feature-' + features[i].bit + '">' + '<label for="feature-' + fcFeatures[i].bit + '">' +
'<span data-i18n="feature' + features[i].name + '"></span>' + '<span data-i18n="feature' + fcFeatures[i].name + '"></span>' +
'</label>' + '</label>' +
feature_tip_html + feature_tip_html +
'</div>'); '</div>');
features_e.each(function () { features_e.each(function () {
if ($(this).hasClass(features[i].group)) { if ($(this).hasClass(fcFeatures[i].group)) {
$(this).after(row_e); $(this).after(row_e);
} }
}); });
} }
helper.features.updateUI($('.tab-configuration'), FEATURES); features.updateUI($('.tab-configuration'), FC.FEATURES);
// translate to user-selected language // translate to user-selected language
i18n.localize();; i18n.localize();;
// VTX // VTX
var config_vtx = $('.config-vtx'); var config_vtx = $('.config-vtx');
if (VTX_CONFIG.device_type != VTX.DEV_UNKNOWN) { if (FC.VTX_CONFIG.device_type != VTX.DEV_UNKNOWN) {
var vtx_band = $('#vtx_band'); var vtx_band = $('#vtx_band');
vtx_band.empty(); vtx_band.empty();
var vtx_no_band_note = $('#vtx_no_band'); var vtx_no_band_note = $('#vtx_no_band');
if (VTX_CONFIG.band < VTX.BAND_MIN || VTX_CONFIG.band > VTX.BAND_MAX) { if (FC.VTX_CONFIG.band < VTX.BAND_MIN || FC.VTX_CONFIG.band > VTX.BAND_MAX) {
var noBandName = i18n.getMessage("configurationNoBand"); var noBandName = i18n.getMessage("configurationNoBand");
$('<option value="0">' + noBandName + '</option>').appendTo(vtx_band); $('<option value="0">' + noBandName + '</option>').appendTo(vtx_band);
vtx_no_band_note.show(); vtx_no_band_note.show();
@ -128,41 +141,41 @@ TABS.configuration.initialize = function (callback, scrollPosition) {
for (var ii = 0; ii < VTX.BANDS.length; ii++) { for (var ii = 0; ii < VTX.BANDS.length; ii++) {
var band_name = VTX.BANDS[ii].name; var band_name = VTX.BANDS[ii].name;
var option = $('<option value="' + VTX.BANDS[ii].code + '">' + band_name + '</option>'); var option = $('<option value="' + VTX.BANDS[ii].code + '">' + band_name + '</option>');
if (VTX.BANDS[ii].code == VTX_CONFIG.band) { if (VTX.BANDS[ii].code == FC.VTX_CONFIG.band) {
option.prop('selected', true); option.prop('selected', true);
} }
option.appendTo(vtx_band); option.appendTo(vtx_band);
} }
vtx_band.on('change', function () { vtx_band.on('change', function () {
VTX_CONFIG.band = parseInt($(this).val()); FC.VTX_CONFIG.band = parseInt($(this).val());
}); });
var vtx_channel = $('#vtx_channel'); var vtx_channel = $('#vtx_channel');
vtx_channel.empty(); vtx_channel.empty();
for (var ii = VTX.CHANNEL_MIN; ii <= VTX.CHANNEL_MAX; ii++) { for (var ii = VTX.CHANNEL_MIN; ii <= VTX.CHANNEL_MAX; ii++) {
var option = $('<option value="' + ii + '">' + ii + '</option>'); var option = $('<option value="' + ii + '">' + ii + '</option>');
if (ii == VTX_CONFIG.channel) { if (ii == FC.VTX_CONFIG.channel) {
option.prop('selected', true); option.prop('selected', true);
} }
option.appendTo(vtx_channel); option.appendTo(vtx_channel);
} }
vtx_channel.on('change', function () { vtx_channel.on('change', function () {
VTX_CONFIG.channel = parseInt($(this).val()); FC.VTX_CONFIG.channel = parseInt($(this).val());
}); });
var vtx_power = $('#vtx_power'); var vtx_power = $('#vtx_power');
vtx_power.empty(); vtx_power.empty();
var minPower = VTX.getMinPower(VTX_CONFIG.device_type); var minPower = VTX.getMinPower(FC.VTX_CONFIG.device_type);
var maxPower = VTX.getMaxPower(VTX_CONFIG.device_type); var maxPower = VTX.getMaxPower(FC.VTX_CONFIG.device_type);
for (var ii = minPower; ii <= maxPower; ii++) { for (var ii = minPower; ii <= maxPower; ii++) {
var option = $('<option value="' + ii + '">' + ii + '</option>'); var option = $('<option value="' + ii + '">' + ii + '</option>');
if (ii == VTX_CONFIG.power) { if (ii == FC.VTX_CONFIG.power) {
option.prop('selected', true); option.prop('selected', true);
} }
option.appendTo(vtx_power); option.appendTo(vtx_power);
} }
vtx_power.on('change', function () { vtx_power.on('change', function () {
VTX_CONFIG.power = parseInt($(this).val()); FC.FC.VTX_CONFIG.power = parseInt($(this).val());
}); });
var vtx_low_power_disarm = $('#vtx_low_power_disarm'); var vtx_low_power_disarm = $('#vtx_low_power_disarm');
@ -173,13 +186,13 @@ TABS.configuration.initialize = function (callback, scrollPosition) {
name = ii; name = ii;
} }
var option = $('<option value="' + ii + '">' + name + '</option>'); var option = $('<option value="' + ii + '">' + name + '</option>');
if (ii == VTX_CONFIG.low_power_disarm) { if (ii == FC.VTX_CONFIG.low_power_disarm) {
option.prop('selected', true); option.prop('selected', true);
} }
option.appendTo(vtx_low_power_disarm); option.appendTo(vtx_low_power_disarm);
} }
vtx_low_power_disarm.on('change', function () { vtx_low_power_disarm.on('change', function () {
VTX_CONFIG.low_power_disarm = parseInt($(this).val()); FC.VTX_CONFIG.low_power_disarm = parseInt($(this).val());
}); });
config_vtx.show(); config_vtx.show();
@ -194,32 +207,32 @@ TABS.configuration.initialize = function (callback, scrollPosition) {
$('#content').scrollTop((scrollPosition) ? scrollPosition : 0); $('#content').scrollTop((scrollPosition) ? scrollPosition : 0);
// fill board alignment // fill board alignment
$('input[name="board_align_yaw"]').val((BOARD_ALIGNMENT.yaw / 10.0).toFixed(1)); $('input[name="board_align_yaw"]').val((FC.BOARD_ALIGNMENT.yaw / 10.0).toFixed(1));
// fill magnetometer // fill magnetometer
//UPDATE: moved to GPS tab and hidden //UPDATE: moved to GPS tab and hidden
//$('#mag_declination').val(MISC.mag_declination); //$('#mag_declination').val(FC.MISC.mag_declination);
// fill battery voltage // fill battery voltage
$('#voltagesource').val(MISC.voltage_source); $('#voltagesource').val(FC.MISC.voltage_source);
$('#cells').val(MISC.battery_cells); $('#cells').val(FC.MISC.battery_cells);
$('#celldetectvoltage').val(MISC.vbatdetectcellvoltage); $('#celldetectvoltage').val(FC.MISC.vbatdetectcellvoltage);
$('#mincellvoltage').val(MISC.vbatmincellvoltage); $('#mincellvoltage').val(FC.MISC.vbatmincellvoltage);
$('#maxcellvoltage').val(MISC.vbatmaxcellvoltage); $('#maxcellvoltage').val(FC.MISC.vbatmaxcellvoltage);
$('#warningcellvoltage').val(MISC.vbatwarningcellvoltage); $('#warningcellvoltage').val(FC.MISC.vbatwarningcellvoltage);
$('#voltagescale').val(MISC.vbatscale); $('#voltagescale').val(FC.MISC.vbatscale);
// fill current // fill current
$('#currentscale').val(CURRENT_METER_CONFIG.scale); $('#currentscale').val(FC.CURRENT_METER_CONFIG.scale);
$('#currentoffset').val(CURRENT_METER_CONFIG.offset / 10); $('#currentoffset').val(FC.CURRENT_METER_CONFIG.offset / 10);
// fill battery capacity // fill battery capacity
$('#battery_capacity').val(MISC.battery_capacity); $('#battery_capacity').val(FC.MISC.battery_capacity);
let batCapWarn = Math.round(MISC.battery_capacity_warning * 100 / MISC.battery_capacity); let batCapWarn = Math.round(FC.MISC.battery_capacity_warning * 100 / FC.MISC.battery_capacity);
$('#battery_capacity_warning').val(isNaN(batCapWarn) ? "" : batCapWarn); $('#battery_capacity_warning').val(isNaN(batCapWarn) ? "" : batCapWarn);
let batCapWarnCrit = Math.round(MISC.battery_capacity_critical * 100 / MISC.battery_capacity); let batCapWarnCrit = Math.round(FC.MISC.battery_capacity_critical * 100 / FC.MISC.battery_capacity);
$('#battery_capacity_critical').val(isNaN(batCapWarnCrit) ? "" : batCapWarnCrit); $('#battery_capacity_critical').val(isNaN(batCapWarnCrit) ? "" : batCapWarnCrit);
$('#battery_capacity_unit').val(MISC.battery_capacity_unit); $('#battery_capacity_unit').val(FC.MISC.battery_capacity_unit);
let $i2cSpeed = $('#i2c_speed'), let $i2cSpeed = $('#i2c_speed'),
$i2cSpeedInfo = $('#i2c_speed-info'); $i2cSpeedInfo = $('#i2c_speed-info');
@ -256,33 +269,32 @@ TABS.configuration.initialize = function (callback, scrollPosition) {
$('a.save').on('click', function () { $('a.save').on('click', function () {
//UPDATE: moved to GPS tab and hidden //UPDATE: moved to GPS tab and hidden
//MISC.mag_declination = parseFloat($('#mag_declination').val()); //FC.MISC.mag_declination = parseFloat($('#mag_declination').val());
MISC.battery_cells = parseInt($('#cells').val()); FC.MISC.battery_cells = parseInt($('#cells').val());
MISC.voltage_source = parseInt($('#voltagesource').val()); FC.MISC.voltage_source = parseInt($('#voltagesource').val());
MISC.vbatdetectcellvoltage = parseFloat($('#celldetectvoltage').val()); FC.MISC.vbatdetectcellvoltage = parseFloat($('#celldetectvoltage').val());
MISC.vbatmincellvoltage = parseFloat($('#mincellvoltage').val()); FC.MISC.vbatmincellvoltage = parseFloat($('#mincellvoltage').val());
MISC.vbatmaxcellvoltage = parseFloat($('#maxcellvoltage').val()); FC.MISC.vbatmaxcellvoltage = parseFloat($('#maxcellvoltage').val());
MISC.vbatwarningcellvoltage = parseFloat($('#warningcellvoltage').val()); FC.MISC.vbatwarningcellvoltage = parseFloat($('#warningcellvoltage').val());
MISC.vbatscale = parseInt($('#voltagescale').val()); FC.MISC.vbatscale = parseInt($('#voltagescale').val());
MISC.battery_capacity = parseInt($('#battery_capacity').val()); FC.MISC.battery_capacity = parseInt($('#battery_capacity').val());
MISC.battery_capacity_warning = parseInt($('#battery_capacity_warning').val() * MISC.battery_capacity / 100); FC.MISC.battery_capacity_warning = parseInt($('#battery_capacity_warning').val() * FC.MISC.battery_capacity / 100);
MISC.battery_capacity_critical = parseInt($('#battery_capacity_critical').val() * MISC.battery_capacity / 100); FC.MISC.battery_capacity_critical = parseInt($('#battery_capacity_critical').val() * FC.MISC.battery_capacity / 100);
MISC.battery_capacity_unit = $('#battery_capacity_unit').val(); FC.MISC.battery_capacity_unit = $('#battery_capacity_unit').val();
helper.features.reset(); features.reset();
helper.features.fromUI($('.tab-configuration')); features.fromUI($('.tab-configuration'));
helper.features.execute(function () { features.execute(function () {
CURRENT_METER_CONFIG.scale = parseInt($('#currentscale').val()); FC.CURRENT_METER_CONFIG.scale = parseInt($('#currentscale').val());
CURRENT_METER_CONFIG.offset = Math.round(parseFloat($('#currentoffset').val()) * 10); FC.CURRENT_METER_CONFIG.offset = Math.round(parseFloat($('#currentoffset').val()) * 10);
saveChainer.execute(); saveChainer.execute();
}); });
}); });
interval.add('config_load_analog', function () {
helper.interval.add('config_load_analog', function () { $('#batteryvoltage').val([FC.ANALOG.voltage.toFixed(2)]);
$('#batteryvoltage').val([ANALOG.voltage.toFixed(2)]); $('#batterycurrent').val([FC.ANALOG.amperage.toFixed(2)]);
$('#batterycurrent').val([ANALOG.amperage.toFixed(2)]);
}, 100, true); // 10 fps }, 100, true); // 10 fps
GUI.content_ready(callback); GUI.content_ready(callback);

View file

@ -1,6 +1,18 @@
/*global chrome,helper,mspHelper*/
'use strict'; 'use strict';
const path = require('path');
const MSPChainerClass = require('./../js/msp/MSPchainer');
const mspHelper = require('./../js/msp/MSPHelper');
const MSPCodes = require('./../js/msp/MSPCodes');
const MSP = require('./../js/msp');
const { GUI, TABS } = require('./../js/gui');
const FC = require('./../js/fc');
const Settings = require('./../js/settings');
const i18n = require('./../js/localization');
const tabs = require('./../js/tabs');
const features = require('./../js/feature_framework');
TABS.ez_tune = { TABS.ez_tune = {
}; };
@ -50,7 +62,7 @@ TABS.ez_tune.initialize = function (callback) {
} }
function load_html() { function load_html() {
GUI.load(path.join(__dirname, "tabs/ez_tune.html"), Settings.processHtml(process_html)); GUI.load(path.join(__dirname, "ez_tune.html"), Settings.processHtml(process_html));
} }
function getYawPidScale(input) { function getYawPidScale(input) {
@ -103,20 +115,20 @@ TABS.ez_tune.initialize = function (callback) {
function process_html() { function process_html() {
i18n.localize();; i18n.localize();;
helper.tabs.init($('.tab-ez_tune')); tabs.init($('.tab-ez_tune'));
helper.features.updateUI($('.tab-ez_tune'), FEATURES); features.updateUI($('.tab-ez_tune'), FC.FEATURES);
$("#ez_tune_enabled").prop('checked', EZ_TUNE.enabled); $("#ez_tune_enabled").prop('checked', FC.EZ_TUNE.enabled);
GUI.sliderize($('#ez_tune_filter_hz'), EZ_TUNE.filterHz, 10, 300); GUI.sliderize($('#ez_tune_filter_hz'), FC.EZ_TUNE.filterHz, 10, 300);
GUI.sliderize($('#ez_tune_axis_ratio'), EZ_TUNE.axisRatio, 25, 175); GUI.sliderize($('#ez_tune_axis_ratio'), FC.EZ_TUNE.axisRatio, 25, 175);
GUI.sliderize($('#ez_tune_response'), EZ_TUNE.response, 0, 200); GUI.sliderize($('#ez_tune_response'), FC.EZ_TUNE.response, 0, 200);
GUI.sliderize($('#ez_tune_damping'), EZ_TUNE.damping, 0, 200); GUI.sliderize($('#ez_tune_damping'), FC.EZ_TUNE.damping, 0, 200);
GUI.sliderize($('#ez_tune_stability'), EZ_TUNE.stability, 0, 200); GUI.sliderize($('#ez_tune_stability'), FC.EZ_TUNE.stability, 0, 200);
GUI.sliderize($('#ez_tune_aggressiveness'), EZ_TUNE.aggressiveness, 0, 200); GUI.sliderize($('#ez_tune_aggressiveness'), FC.EZ_TUNE.aggressiveness, 0, 200);
GUI.sliderize($('#ez_tune_rate'), EZ_TUNE.rate, 0, 200); GUI.sliderize($('#ez_tune_rate'), FC.EZ_TUNE.rate, 0, 200);
GUI.sliderize($('#ez_tune_expo'), EZ_TUNE.expo, 0, 200); GUI.sliderize($('#ez_tune_expo'), FC.EZ_TUNE.expo, 0, 200);
$('.ez-element').on('updated', function () { $('.ez-element').on('updated', function () {
@ -132,19 +144,19 @@ TABS.ez_tune.initialize = function (callback) {
$('a.update').on('click', function () { $('a.update').on('click', function () {
if ($("#ez_tune_enabled").is(":checked")) { if ($("#ez_tune_enabled").is(":checked")) {
EZ_TUNE.enabled = 1; FC.EZ_TUNE.enabled = 1;
} else { } else {
EZ_TUNE.enabled = 0; FC.EZ_TUNE.enabled = 0;
} }
EZ_TUNE.filterHz = $('#ez_tune_filter_hz').val(); FC.EZ_TUNE.filterHz = $('#ez_tune_filter_hz').val();
EZ_TUNE.axisRatio = $('#ez_tune_axis_ratio').val(); FC.EZ_TUNE.axisRatio = $('#ez_tune_axis_ratio').val();
EZ_TUNE.response = $('#ez_tune_response').val(); FC.EZ_TUNE.response = $('#ez_tune_response').val();
EZ_TUNE.damping = $('#ez_tune_damping').val(); FC.EZ_TUNE.damping = $('#ez_tune_damping').val();
EZ_TUNE.stability = $('#ez_tune_stability').val(); FC.EZ_TUNE.stability = $('#ez_tune_stability').val();
EZ_TUNE.aggressiveness = $('#ez_tune_aggressiveness').val(); FC.EZ_TUNE.aggressiveness = $('#ez_tune_aggressiveness').val();
EZ_TUNE.rate = $('#ez_tune_rate').val(); FC.EZ_TUNE.rate = $('#ez_tune_rate').val();
EZ_TUNE.expo = $('#ez_tune_expo').val(); FC.EZ_TUNE.expo = $('#ez_tune_expo').val();
saveChainer.execute(); saveChainer.execute();
}); });

View file

@ -1,5 +1,15 @@
'use strict'; 'use strict';
const path = require('path');
const mspHelper = require('./../js/msp/MSPHelper');
const MSPCodes = require('./../js/msp/MSPCodes');
const MSP = require('./../js/msp');
const { GUI, TABS } = require('./../js/gui');
const FC = require('./../js/fc');
const Settings = require('./../js/settings');
const i18n = require('./../js/localization');
TABS.failsafe = {}; TABS.failsafe = {};
TABS.failsafe.initialize = function (callback, scrollPosition) { TABS.failsafe.initialize = function (callback, scrollPosition) {
@ -14,7 +24,7 @@ TABS.failsafe.initialize = function (callback, scrollPosition) {
} }
function load_html() { function load_html() {
GUI.load(path.join(__dirname, "tabs/failsafe.html"), Settings.processHtml(function() { GUI.load(path.join(__dirname, "failsafe.html"), Settings.processHtml(function() {
GUI.simpleBind(); GUI.simpleBind();
// translate to user-selected language // translate to user-selected language
@ -48,25 +58,25 @@ TABS.failsafe.initialize = function (callback, scrollPosition) {
}); });
// switch (MSPHelper.getSetting('failsafe_procedure')) { // Use once #7734 is merged // switch (MSPHelper.getSetting('failsafe_procedure')) { // Use once #7734 is merged
switch (FAILSAFE_CONFIG.failsafe_procedure) { switch (FC.FAILSAFE_CONFIG.failsafe_procedure) {
default: default:
case 0: case 0:
let element = $('input[id="land"]'); var element = $('input[id="land"]');
element.prop('checked', true); element.prop('checked', true);
element.trigger('change'); element.trigger('change');
break; break;
case 1: case 1:
element = $('input[id="drop"]'); var element = $('input[id="drop"]');
element.prop('checked', true); element.prop('checked', true);
element.trigger('change'); element.trigger('change');
break; break;
case 2: case 2:
element = $('input[id="rth"]'); var element = $('input[id="rth"]');
element.prop('checked', true); element.prop('checked', true);
element.trigger('change'); element.trigger('change');
break; break;
case 3: case 3:
element = $('input[id="nothing"]'); var element = $('input[id="nothing"]');
element.prop('checked', true); element.prop('checked', true);
element.trigger('change'); element.trigger('change');
break; break;
@ -99,13 +109,13 @@ TABS.failsafe.initialize = function (callback, scrollPosition) {
$('a.save').on('click', function () { $('a.save').on('click', function () {
if ($('input[id="land"]').is(':checked')) { if ($('input[id="land"]').is(':checked')) {
FAILSAFE_CONFIG.failsafe_procedure = 0; FC.FAILSAFE_CONFIG.failsafe_procedure = 0;
} else if ($('input[id="drop"]').is(':checked')) { } else if ($('input[id="drop"]').is(':checked')) {
FAILSAFE_CONFIG.failsafe_procedure = 1; FC.FAILSAFE_CONFIG.failsafe_procedure = 1;
} else if ($('input[id="rth"]').is(':checked')) { } else if ($('input[id="rth"]').is(':checked')) {
FAILSAFE_CONFIG.failsafe_procedure = 2; FC.FAILSAFE_CONFIG.failsafe_procedure = 2;
} else if ($('input[id="nothing"]').is(':checked')) { } else if ($('input[id="nothing"]').is(':checked')) {
FAILSAFE_CONFIG.failsafe_procedure = 3; FC.FAILSAFE_CONFIG.failsafe_procedure = 3;
} }
MSP.send_message(MSPCodes.MSP_SET_FAILSAFE_CONFIG, mspHelper.crunch(MSPCodes.MSP_SET_FAILSAFE_CONFIG), false, savePhaseTwo); MSP.send_message(MSPCodes.MSP_SET_FAILSAFE_CONFIG, mspHelper.crunch(MSPCodes.MSP_SET_FAILSAFE_CONFIG), false, savePhaseTwo);
@ -122,7 +132,7 @@ TABS.failsafe.initialize = function (callback, scrollPosition) {
var self = this; var self = this;
MSP.promise(MSPCodes.MSP_EEPROM_WRITE); MSP.promise(MSPCodes.MSP_EEPROM_WRITE);
setTimeout(function () { setTimeout(function () {
$(self).html(oldText); $(self).html('');
}, 2000); }, 2000);
reboot(); reboot();
}); });

View file

@ -1,6 +1,26 @@
/*global $,MSPChainerClass,mspHelper,MSPCodes,GUI,chrome,MSP,TABS,Settings,helper,ol*/
'use strict'; 'use strict';
const path = require('path')
const ol = require('openlayers')
const semver = require('semver');
const MSPChainerClass = require('./../js/msp/MSPchainer');
const mspHelper = require('./../js/msp/MSPHelper');
const MSPCodes = require('./../js/msp/MSPCodes');
const MSP = require('./../js/msp');
const mspBalancedInterval = require('./../js/msp_balanced_interval.js');
const mspQueue = require('./../js/serial_queue.js');
const { GUI, TABS } = require('./../js/gui');
const FC = require('./../js/fc');
const i18n = require('./../js/localization');
const Settings = require('./../js/settings');
const serialPortHelper = require('./../js/serialPortHelper');
const features = require('./../js/feature_framework');
const { globalSettings } = require('./../js/globalSettings');
const jBox = require('./../js/libraries/jBox/jBox.min.js');
const SerialBackend = require('../js/serial_backend');
TABS.gps = {}; TABS.gps = {};
TABS.gps.initialize = function (callback) { TABS.gps.initialize = function (callback) {
@ -74,7 +94,7 @@ TABS.gps.initialize = function (callback) {
} }
function load_html() { function load_html() {
GUI.load(path.join(__dirname, "tabs/gps.html"), Settings.processHtml(process_html)); GUI.load(path.join(__dirname, "gps.html"), Settings.processHtml(process_html));
} }
let cursorInitialized = false; let cursorInitialized = false;
@ -89,15 +109,15 @@ TABS.gps.initialize = function (callback) {
function process_html() { function process_html() {
i18n.localize();; i18n.localize();;
var features = FC.getFeatures(); var fcFeatures = FC.getFeatures();
helper.features.updateUI($('.tab-gps'), FEATURES); features.updateUI($('.tab-gps'), FC.FEATURES);
//Generate serial port options //Generate serial port options
let $port = $('#gps_port'); let $port = $('#gps_port');
let $baud = $('#gps_baud'); let $baud = $('#gps_baud');
let ports = helper.serialPortHelper.getPortIdentifiersForFunction('GPS'); let ports = serialPortHelper.getPortIdentifiersForFunction('GPS');
let currentPort = null; let currentPort = null;
@ -105,7 +125,7 @@ TABS.gps.initialize = function (callback) {
currentPort = ports[0]; currentPort = ports[0];
} }
let availablePorts = helper.serialPortHelper.getPortList(); let availablePorts = serialPortHelper.getPortList();
//Generate port select //Generate port select
$port.append('<option value="-1">NONE</option>'); $port.append('<option value="-1">NONE</option>');
@ -115,18 +135,18 @@ TABS.gps.initialize = function (callback) {
} }
//Generate baud select //Generate baud select
helper.serialPortHelper.getBauds('SENSOR').forEach(function (baud) { serialPortHelper.getBauds('SENSOR').forEach(function (baud) {
$baud.append('<option value="' + baud + '">' + baud + '</option>'); $baud.append('<option value="' + baud + '">' + baud + '</option>');
}); });
//Select defaults //Select defaults
if (currentPort !== null) { if (currentPort !== null) {
$port.val(currentPort); $port.val(currentPort);
let portConfig = helper.serialPortHelper.getPortByIdentifier(currentPort); let portConfig = serialPortHelper.getPortByIdentifier(currentPort);
$baud.val(portConfig.sensors_baudrate); $baud.val(portConfig.sensors_baudrate);
} else { } else {
$port.val(-1); $port.val(-1);
$baud.val(helper.serialPortHelper.getRuleByName('GPS').defaultBaud); $baud.val(serialPortHelper.getRuleByName('GPS').defaultBaud);
} }
// generate GPS // generate GPS
@ -139,10 +159,10 @@ TABS.gps.initialize = function (callback) {
} }
gps_protocol_e.on('change', function () { gps_protocol_e.on('change', function () {
MISC.gps_type = parseInt($(this).val()); FC.MISC.gps_type = parseInt($(this).val());
}); });
gps_protocol_e.val(MISC.gps_type); gps_protocol_e.val(FC.MISC.gps_type);
gps_protocol_e.trigger('change'); gps_protocol_e.trigger('change');
var gps_ubx_sbas_e = $('#gps_ubx_sbas'); var gps_ubx_sbas_e = $('#gps_ubx_sbas');
@ -151,10 +171,10 @@ TABS.gps.initialize = function (callback) {
} }
gps_ubx_sbas_e.on('change', function () { gps_ubx_sbas_e.on('change', function () {
MISC.gps_ubx_sbas = parseInt($(this).val()); FC.MISC.gps_ubx_sbas = parseInt($(this).val());
}); });
gps_ubx_sbas_e.val(MISC.gps_ubx_sbas); gps_ubx_sbas_e.val(FC.MISC.gps_ubx_sbas);
let mapView = new ol.View({ let mapView = new ol.View({
center: ol.proj.fromLonLat([0, 0]), center: ol.proj.fromLonLat([0, 0]),
@ -179,8 +199,8 @@ TABS.gps.initialize = function (callback) {
} }
$("#center_button").on('click', function () { $("#center_button").on('click', function () {
let lat = GPS_DATA.lat / 10000000; let lat = FC.GPS_DATA.lat / 10000000;
let lon = GPS_DATA.lon / 10000000; let lon = FC.GPS_DATA.lon / 10000000;
let center = ol.proj.fromLonLat([lon, lat]); let center = ol.proj.fromLonLat([lon, lat]);
mapView.setCenter(center); mapView.setCenter(center);
}); });
@ -243,39 +263,39 @@ TABS.gps.initialize = function (callback) {
function update_ui() { function update_ui() {
let lat = GPS_DATA.lat / 10000000; let lat = FC.GPS_DATA.lat / 10000000;
let lon = GPS_DATA.lon / 10000000; let lon = FC.GPS_DATA.lon / 10000000;
let gpsFixType = i18n.getMessage('gpsFixNone'); let gpsFixType = i18n.getMessage('gpsFixNone');
if (GPS_DATA.fix >= 2) { if (FC.GPS_DATA.fix >= 2) {
gpsFixType = i18n.getMessage('gpsFix3D'); gpsFixType = i18n.getMessage('gpsFix3D');
} else if (GPS_DATA.fix >= 1) { } else if (FC.GPS_DATA.fix >= 1) {
gpsFixType = i18n.getMessage('gpsFix2D'); gpsFixType = i18n.getMessage('gpsFix2D');
} }
$('.GPS_info td.fix').html(gpsFixType); $('.GPS_info td.fix').html(gpsFixType);
$('.GPS_info td.alt').text(GPS_DATA.alt + ' m'); $('.GPS_info td.alt').text(FC.GPS_DATA.alt + ' m');
$('.GPS_info td.lat').text(lat.toFixed(4) + ' deg'); $('.GPS_info td.lat').text(lat.toFixed(4) + ' deg');
$('.GPS_info td.lon').text(lon.toFixed(4) + ' deg'); $('.GPS_info td.lon').text(lon.toFixed(4) + ' deg');
$('.GPS_info td.speed').text(GPS_DATA.speed + ' cm/s'); $('.GPS_info td.speed').text(FC.GPS_DATA.speed + ' cm/s');
$('.GPS_info td.sats').text(GPS_DATA.numSat); $('.GPS_info td.sats').text(FC.GPS_DATA.numSat);
$('.GPS_info td.distToHome').text(GPS_DATA.distanceToHome + ' m'); $('.GPS_info td.distToHome').text(FC.GPS_DATA.distanceToHome + ' m');
let gpsRate = 0; let gpsRate = 0;
if (GPS_DATA.messageDt > 0) { if (FC.GPS_DATA.messageDt > 0) {
gpsRate = 1000 / GPS_DATA.messageDt; gpsRate = 1000 / FC.GPS_DATA.messageDt;
} }
$('.GPS_stat td.messages').text(GPS_DATA.packetCount); $('.GPS_stat td.messages').text(FC.GPS_DATA.packetCount);
$('.GPS_stat td.rate').text(gpsRate.toFixed(1) + ' Hz'); $('.GPS_stat td.rate').text(gpsRate.toFixed(1) + ' Hz');
$('.GPS_stat td.errors').text(GPS_DATA.errors); $('.GPS_stat td.errors').text(FC.GPS_DATA.errors);
$('.GPS_stat td.timeouts').text(GPS_DATA.timeouts); $('.GPS_stat td.timeouts').text(FC.GPS_DATA.timeouts);
$('.GPS_stat td.eph').text((GPS_DATA.eph / 100).toFixed(2) + ' m'); $('.GPS_stat td.eph').text((FC.GPS_DATA.eph / 100).toFixed(2) + ' m');
$('.GPS_stat td.epv').text((GPS_DATA.epv / 100).toFixed(2) + ' m'); $('.GPS_stat td.epv').text((FC.GPS_DATA.epv / 100).toFixed(2) + ' m');
$('.GPS_stat td.hdop').text((GPS_DATA.hdop / 100).toFixed(2)); $('.GPS_stat td.hdop').text((FC.GPS_DATA.hdop / 100).toFixed(2));
//Update map //Update map
if (GPS_DATA.fix >= 2) { if (FC.GPS_DATA.fix >= 2) {
let center = ol.proj.fromLonLat([lon, lat]); let center = ol.proj.fromLonLat([lon, lat]);
@ -316,7 +336,7 @@ TABS.gps.initialize = function (callback) {
} }
if (semver.gte(CONFIG.flightControllerVersion, "7.1.0")) { if (semver.gte(FC.CONFIG.flightControllerVersion, "7.1.0")) {
MSP.send_message(MSPCodes.MSP2_ADSB_VEHICLE_LIST, false, false, function () { MSP.send_message(MSPCodes.MSP2_ADSB_VEHICLE_LIST, false, false, function () {
//ADSB vehicles //ADSB vehicles
@ -324,8 +344,8 @@ TABS.gps.initialize = function (callback) {
vehicleVectorSource.clear(); vehicleVectorSource.clear();
} }
for (let key in ADSB_VEHICLES.vehicles) { for (let key in FC.ADSB_VEHICLES.vehicles) {
let vehicle = ADSB_VEHICLES.vehicles[key]; let vehicle = FC.ADSB_VEHICLES.vehicles[key];
if (!vehiclesCursorInitialized) { if (!vehiclesCursorInitialized) {
vehiclesCursorInitialized = true; vehiclesCursorInitialized = true;
@ -380,14 +400,14 @@ TABS.gps.initialize = function (callback) {
* enable data pulling * enable data pulling
* GPS is usually refreshed at 5Hz, there is no reason to pull it much more often, really... * GPS is usually refreshed at 5Hz, there is no reason to pull it much more often, really...
*/ */
helper.mspBalancedInterval.add('gps_pull', 200, 3, function gps_update() { mspBalancedInterval.add('gps_pull', 200, 3, function gps_update() {
// avoid usage of the GPS commands until a GPS sensor is detected for targets that are compiled without GPS support. // avoid usage of the GPS commands until a GPS sensor is detected for targets that are compiled without GPS support.
if (!have_sensor(CONFIG.activeSensors, 'gps')) { if (!SerialBackend.have_sensor(FC.CONFIG.activeSensors, 'gps')) {
update_ui(); update_ui();
return; return;
} }
if (helper.mspQueue.shouldDrop()) { if (mspQueue.shouldDrop()) {
return; return;
} }
@ -396,25 +416,10 @@ TABS.gps.initialize = function (callback) {
$('a.save').on('click', function () { $('a.save').on('click', function () {
if (FC.isFeatureEnabled('GPS', features)) { serialPortHelper.set($port.val(), 'GPS', $baud.val());
googleAnalytics.sendEvent('Setting', 'GpsProtocol', gpsProtocols[MISC.gps_type]); features.reset();
googleAnalytics.sendEvent('Setting', 'GpsSbas', gpsSbas[MISC.gps_ubx_sbas]); features.fromUI($('.tab-gps'));
} features.execute(function () {
googleAnalytics.sendEvent('Setting', 'GPSEnabled', FC.isFeatureEnabled('GPS', features) ? "true" : "false");
for (var i = 0; i < features.length; i++) {
var featureName = features[i].name;
if (FC.isFeatureEnabled(featureName, features)) {
googleAnalytics.sendEvent('Setting', 'Feature', featureName);
}
}
helper.serialPortHelper.set($port.val(), 'GPS', $baud.val());
helper.features.reset();
helper.features.fromUI($('.tab-gps'));
helper.features.execute(function () {
saveChainer.execute(); saveChainer.execute();
}); });
}); });

View file

@ -12,13 +12,6 @@ landing.initialize = function (callback) {
} }
GUI.load(path.join(__dirname, "landing.html"), function () { GUI.load(path.join(__dirname, "landing.html"), function () {
i18n.localize(); i18n.localize();
/*
$('.tab-landing a').on('click', function () {
googleAnalytics.sendEvent('ExternalUrls', 'Click', $(this).prop('href'));
});
*/
GUI.content_ready(callback); GUI.content_ready(callback);
}); });
@ -28,5 +21,4 @@ landing.cleanup = function (callback) {
if (callback) callback(); if (callback) callback();
}; };
TABS.landing = landing; TABS.landing = landing;
module.exports = landing;

View file

@ -1,5 +1,14 @@
'use strict'; 'use strict';
const path = require('path');
const mspHelper = require('./../js/msp/MSPHelper');
const MSPCodes = require('./../js/msp/MSPCodes');
const MSP = require('./../js/msp');
const { GUI, TABS } = require('./../js/gui');
const FC = require('./../js/fc');
const i18n = require('./../js/localization');
TABS.led_strip = { TABS.led_strip = {
wireMode: false, wireMode: false,
directions: ['n', 'e', 's', 'w', 'u', 'd'], directions: ['n', 'e', 's', 'w', 'u', 'd'],
@ -34,7 +43,7 @@ TABS.led_strip.initialize = function (callback, scrollPosition) {
} }
function load_html() { function load_html() {
GUI.load(path.join(__dirname, "tabs/led_strip.html"), process_html); GUI.load(path.join(__dirname, "led_strip.html"), process_html);
} }
load_led_config(); load_led_config();
@ -132,7 +141,7 @@ TABS.led_strip.initialize = function (callback, scrollPosition) {
// Mode Color Buttons // Mode Color Buttons
$('.mode_colors').on('click', 'button', function() { $('.mode_colors').on('click', 'button', function() {
var that = this; var that = this;
LED_MODE_COLORS.forEach(function(mc) { FC.LED_MODE_COLORS.forEach(function(mc) {
if ($(that).is('.mode_color-' + mc.mode + '-' + mc.direction)) { if ($(that).is('.mode_color-' + mc.mode + '-' + mc.direction)) {
if ($(that).is('.btnOn')) { if ($(that).is('.btnOn')) {
$(that).removeClass('btnOn'); $(that).removeClass('btnOn');
@ -286,7 +295,7 @@ TABS.led_strip.initialize = function (callback, scrollPosition) {
} }
if (TABS.led_strip.wireMode) { if (TABS.led_strip.wireMode) {
if ($(this).find('.wire').html() == '' && nextWireNumber < LED_STRIP.length) { if ($(this).find('.wire').html() == '' && nextWireNumber < FC.LED_STRIP.length) {
$(this).find('.wire').html(nextWireNumber); $(this).find('.wire').html(nextWireNumber);
} }
} }
@ -562,8 +571,8 @@ TABS.led_strip.initialize = function (callback, scrollPosition) {
function findLed(x, y) { function findLed(x, y) {
for (var ledIndex = 0; ledIndex < LED_STRIP.length; ledIndex++) { for (var ledIndex = 0; ledIndex < FC.LED_STRIP.length; ledIndex++) {
var led = LED_STRIP[ledIndex]; var led = FC.LED_STRIP[ledIndex];
if (led.x == x && led.y == y) { if (led.x == x && led.y == y) {
return { index: ledIndex, led: led }; return { index: ledIndex, led: led };
} }
@ -576,11 +585,11 @@ TABS.led_strip.initialize = function (callback, scrollPosition) {
var counter = 0; var counter = 0;
var lines = []; var lines = [];
var ledStripLength = LED_STRIP.length; var ledStripLength = FC.LED_STRIP.length;
var ledColorsLength = LED_COLORS.length; var ledColorsLength = FC.LED_COLORS.length;
var ledModeColorsLenggth = LED_MODE_COLORS.length; var ledModeColorsLenggth = FC.LED_MODE_COLORS.length;
LED_STRIP = []; FC.LED_STRIP = [];
$('.gPoint').each(function(){ $('.gPoint').each(function(){
if ($(this).is('[class*="function"]')) { if ($(this).is('[class*="function"]')) {
@ -626,7 +635,7 @@ TABS.led_strip.initialize = function (callback, scrollPosition) {
color: colorIndex color: colorIndex
} }
LED_STRIP[wireNumber] = led; FC.LED_STRIP[wireNumber] = led;
} }
counter++; counter++;
} }
@ -640,15 +649,15 @@ TABS.led_strip.initialize = function (callback, scrollPosition) {
}; };
for (var i = 0; i < ledStripLength; i++) { for (var i = 0; i < ledStripLength; i++) {
if (LED_STRIP[i]) { if (FC.LED_STRIP[i]) {
continue; continue;
} }
LED_STRIP[i] = defaultLed; FC.LED_STRIP[i] = defaultLed;
} }
var usedWireNumbers = buildUsedWireNumbers(); var usedWireNumbers = buildUsedWireNumbers();
var remaining = LED_STRIP.length - usedWireNumbers.length; var remaining = FC.LED_STRIP.length - usedWireNumbers.length;
$('.wires-remaining div').html(remaining); $('.wires-remaining div').html(remaining);
} }
@ -663,7 +672,7 @@ TABS.led_strip.initialize = function (callback, scrollPosition) {
if (match) { if (match) {
m = Number(match[2]); m = Number(match[2]);
d = Number(match[3]); d = Number(match[3]);
$(this).css('background-color', HsvToColor(LED_COLORS[getModeColor(m, d)])); $(this).css('background-color', HsvToColor(FC.LED_COLORS[getModeColor(m, d)]));
} }
}); });
} }
@ -675,7 +684,7 @@ TABS.led_strip.initialize = function (callback, scrollPosition) {
var match = element.attr("class").match(/(^|\s)color-([0-9]+)(\s|$)/); var match = element.attr("class").match(/(^|\s)color-([0-9]+)(\s|$)/);
if (match) { if (match) {
colorIndex = match[2]; colorIndex = match[2];
element.css('background-color', HsvToColor(LED_COLORS[colorIndex])); element.css('background-color', HsvToColor(FC.LED_COLORS[colorIndex]));
} }
} }
} }
@ -878,23 +887,23 @@ TABS.led_strip.initialize = function (callback, scrollPosition) {
if ($(className).hasClass('btnOn')) { if ($(className).hasClass('btnOn')) {
switch (hsvIndex) { switch (hsvIndex) {
case 0: case 0:
if (LED_COLORS[selectedColorIndex].h != value) { if (FC.LED_COLORS[selectedColorIndex].h != value) {
LED_COLORS[selectedColorIndex].h = value; FC.LED_COLORS[selectedColorIndex].h = value;
$('.colorDefineSliderValue.Hvalue').text(LED_COLORS[selectedColorIndex].h); $('.colorDefineSliderValue.Hvalue').text(FC.LED_COLORS[selectedColorIndex].h);
change = true change = true
} }
break; break;
case 1: case 1:
if (LED_COLORS[selectedColorIndex].s != value) { if (FC.LED_COLORS[selectedColorIndex].s != value) {
LED_COLORS[selectedColorIndex].s = value; FC.LED_COLORS[selectedColorIndex].s = value;
$('.colorDefineSliderValue.Svalue').text(LED_COLORS[selectedColorIndex].s); $('.colorDefineSliderValue.Svalue').text(FC.LED_COLORS[selectedColorIndex].s);
change = true change = true
} }
break; break;
case 2: case 2:
if (LED_COLORS[selectedColorIndex].v != value) { if (FC.LED_COLORS[selectedColorIndex].v != value) {
LED_COLORS[selectedColorIndex].v = value; FC.LED_COLORS[selectedColorIndex].v = value;
$('.colorDefineSliderValue.Vvalue').text(LED_COLORS[selectedColorIndex].v); $('.colorDefineSliderValue.Vvalue').text(FC.LED_COLORS[selectedColorIndex].v);
change = true change = true
} }
break; break;
@ -922,7 +931,7 @@ TABS.led_strip.initialize = function (callback, scrollPosition) {
var className = 'color-' + colorIndex; var className = 'color-' + colorIndex;
if ($(this).is('.' + className)) { if ($(this).is('.' + className)) {
$(this).find('.overlay-color').addClass(className); $(this).find('.overlay-color').addClass(className);
$(this).find('.overlay-color').css('background-color', HsvToColor(LED_COLORS[colorIndex])) $(this).find('.overlay-color').css('background-color', HsvToColor(FC.LED_COLORS[colorIndex]))
} else { } else {
if ($(this).find('.overlay-color').is('.' + className)) if ($(this).find('.overlay-color').is('.' + className))
$(this).find('.overlay-color').removeClass(className); $(this).find('.overlay-color').removeClass(className);
@ -939,24 +948,24 @@ TABS.led_strip.initialize = function (callback, scrollPosition) {
var sliders = $('div.colorDefineSliders input'); var sliders = $('div.colorDefineSliders input');
var change = false; var change = false;
if (!LED_COLORS[colorIndex]) if (!FC.LED_COLORS[colorIndex])
return; return;
if (LED_COLORS[colorIndex].h != Number(sliders.eq(0).val())) { if (FC.LED_COLORS[colorIndex].h != Number(sliders.eq(0).val())) {
sliders.eq(0).val(LED_COLORS[colorIndex].h); sliders.eq(0).val(FC.LED_COLORS[colorIndex].h);
$('.colorDefineSliderValue.Hvalue').text(LED_COLORS[colorIndex].h); $('.colorDefineSliderValue.Hvalue').text(FC.LED_COLORS[colorIndex].h);
change = true; change = true;
} }
if (LED_COLORS[colorIndex].s != Number(sliders.eq(1).val())) { if (FC.LED_COLORS[colorIndex].s != Number(sliders.eq(1).val())) {
sliders.eq(1).val(LED_COLORS[colorIndex].s); sliders.eq(1).val(FC.LED_COLORS[colorIndex].s);
$('.colorDefineSliderValue.Svalue').text(LED_COLORS[colorIndex].s); $('.colorDefineSliderValue.Svalue').text(FC.LED_COLORS[colorIndex].s);
change = true; change = true;
} }
if (LED_COLORS[colorIndex].v != Number(sliders.eq(2).val())) { if (FC.LED_COLORS[colorIndex].v != Number(sliders.eq(2).val())) {
sliders.eq(2).val(LED_COLORS[colorIndex].v); sliders.eq(2).val(FC.LED_COLORS[colorIndex].v);
$('.colorDefineSliderValue.Vvalue').text(LED_COLORS[colorIndex].v); $('.colorDefineSliderValue.Vvalue').text(FC.LED_COLORS[colorIndex].v);
change = true; change = true;
} }
@ -987,8 +996,8 @@ TABS.led_strip.initialize = function (callback, scrollPosition) {
} }
function getModeColor(mode, dir) { function getModeColor(mode, dir) {
for (var i = 0; i < LED_MODE_COLORS.length; i++) { for (var i = 0; i < FC.LED_MODE_COLORS.length; i++) {
var mc = LED_MODE_COLORS[i]; var mc = FC.LED_MODE_COLORS[i];
if (mc.mode == mode && mc.direction == dir) if (mc.mode == mode && mc.direction == dir)
return mc.color; return mc.color;
} }
@ -996,8 +1005,8 @@ TABS.led_strip.initialize = function (callback, scrollPosition) {
} }
function setModeColor(mode, dir, color) { function setModeColor(mode, dir, color) {
for (var i = 0; i < LED_MODE_COLORS.length; i++) { for (var i = 0; i < FC.LED_MODE_COLORS.length; i++) {
var mc = LED_MODE_COLORS[i]; var mc = FC.LED_MODE_COLORS[i];
if (mc.mode == mode && mc.direction == dir) { if (mc.mode == mode && mc.direction == dir) {
mc.color = color; mc.color = color;
return 1; return 1;

View file

@ -1,5 +1,21 @@
'use strict'; 'use strict';
const path = require('path');
const { dialog } = require("@electron/remote");
const Store = require('electron-store');
const store = new Store();
const MSPCodes = require('./../js/msp/MSPCodes');
const MSP = require('./../js/msp');
const mspBalancedInterval = require('./../js/msp_balanced_interval');
const { GUI, TABS } = require('./../js/gui');
const FC = require('./../js/fc');
const CONFIGURATOR = require('./../js/data_storage');
const interval = require('./../js/intervals');
const i18n = require('./../js/localization');
const { zeroPad } = require('./../js/helpers');
TABS.logging = {}; TABS.logging = {};
TABS.logging.initialize = function (callback) { TABS.logging.initialize = function (callback) {
var self = this; var self = this;
@ -22,7 +38,7 @@ TABS.logging.initialize = function (callback) {
} }
var load_html = function () { var load_html = function () {
GUI.load(path.join(__dirname, "tabs/logging.html"), process_html); GUI.load(path.join(__dirname, "logging.html"), process_html);
} }
MSP.send_message(MSPCodes.MSP_RC, false, false, get_motor_data); MSP.send_message(MSPCodes.MSP_RC, false, false, get_motor_data);
@ -30,7 +46,7 @@ TABS.logging.initialize = function (callback) {
function process_html() { function process_html() {
// translate to user-selected language // translate to user-selected language
i18n.localize();; i18n.localize();;
// UI hooks // UI hooks
$('a.log_file').on('click', prepare_file); $('a.log_file').on('click', prepare_file);
@ -67,9 +83,9 @@ TABS.logging.initialize = function (callback) {
} }
} }
helper.interval.add('log_data_poll', log_data_poll, parseInt($('select.speed').val()), true); // refresh rate goes here interval.add('log_data_poll', log_data_poll, parseInt($('select.speed').val()), true); // refresh rate goes here
const fs = require('fs'); const fs = require('fs');
helper.interval.add('write_data', function write_data() { interval.add('write_data', function write_data() {
if (log_buffer.length && readyToWrite) { // only execute when there is actual data to write if (log_buffer.length && readyToWrite) { // only execute when there is actual data to write
fs.writeFileSync(loggingFileName, log_buffer.join('\n') + '\n', { fs.writeFileSync(loggingFileName, log_buffer.join('\n') + '\n', {
@ -89,8 +105,8 @@ TABS.logging.initialize = function (callback) {
GUI.log(i18n.getMessage('loggingErrorOneProperty')); GUI.log(i18n.getMessage('loggingErrorOneProperty'));
} }
} else { } else {
helper.interval.killAll(['global_data_refresh', 'msp-load-update']); interval.killAll(['global_data_refresh', 'msp-load-update']);
helper.mspBalancedInterval.flush(); mspBalancedInterval.flush();
$('.speed').prop('disabled', false); $('.speed').prop('disabled', false);
$(this).text(i18n.getMessage('loggingStart')); $(this).text(i18n.getMessage('loggingStart'));
@ -149,17 +165,17 @@ TABS.logging.initialize = function (callback) {
head += ',' + 'rssi'; head += ',' + 'rssi';
break; break;
case 'MSP_RC': case 'MSP_RC':
for (var chan = 0; chan < RC.active_channels; chan++) { for (var chan = 0; chan < FC.RC.active_channels; chan++) {
head += ',' + 'RC' + chan; head += ',' + 'RC' + chan;
} }
break; break;
case 'MSP_MOTOR': case 'MSP_MOTOR':
for (var motor = 0; motor < MOTOR_DATA.length; motor++) { for (var motor = 0; motor < FC.MOTOR_DATA.length; motor++) {
head += ',' + 'Motor' + motor; head += ',' + 'Motor' + motor;
} }
break; break;
case 'MSP_DEBUG': case 'MSP_DEBUG':
for (var debug = 0; debug < SENSOR_DATA.debug.length; debug++) { for (var debug = 0; debug < FC.SENSOR_DATA.debug.length; debug++) {
head += ',' + 'Debug' + debug; head += ',' + 'Debug' + debug;
} }
break; break;
@ -174,43 +190,43 @@ TABS.logging.initialize = function (callback) {
for (var i = 0; i < requested_properties.length; i++) { for (var i = 0; i < requested_properties.length; i++) {
switch (requested_properties[i]) { switch (requested_properties[i]) {
case 'MSP_RAW_IMU': case 'MSP_RAW_IMU':
sample += ',' + SENSOR_DATA.gyroscope; sample += ',' + FC.SENSOR_DATA.gyroscope;
sample += ',' + SENSOR_DATA.accelerometer; sample += ',' + FC.SENSOR_DATA.accelerometer;
sample += ',' + SENSOR_DATA.magnetometer; sample += ',' + FC.SENSOR_DATA.magnetometer;
break; break;
case 'MSP_ATTITUDE': case 'MSP_ATTITUDE':
sample += ',' + SENSOR_DATA.kinematics[0]; sample += ',' + FC.SENSOR_DATA.kinematics[0];
sample += ',' + SENSOR_DATA.kinematics[1]; sample += ',' + FC.SENSOR_DATA.kinematics[1];
sample += ',' + SENSOR_DATA.kinematics[2]; sample += ',' + FC.SENSOR_DATA.kinematics[2];
break; break;
case 'MSP_ALTITUDE': case 'MSP_ALTITUDE':
sample += ',' + SENSOR_DATA.altitude; sample += ',' + FC.SENSOR_DATA.altitude;
break; break;
case 'MSP_RAW_GPS': case 'MSP_RAW_GPS':
sample += ',' + GPS_DATA.fix; sample += ',' + FC.GPS_DATA.fix;
sample += ',' + GPS_DATA.numSat; sample += ',' + FC.GPS_DATA.numSat;
sample += ',' + (GPS_DATA.lat / 10000000); sample += ',' + (FC.GPS_DATA.lat / 10000000);
sample += ',' + (GPS_DATA.lon / 10000000); sample += ',' + (FC.GPS_DATA.lon / 10000000);
sample += ',' + GPS_DATA.alt; sample += ',' + FC.GPS_DATA.alt;
sample += ',' + GPS_DATA.speed; sample += ',' + FC.GPS_DATA.speed;
sample += ',' + GPS_DATA.ground_course; sample += ',' + FC.GPS_DATA.ground_course;
break; break;
case 'MSP_ANALOG': case 'MSP_ANALOG':
sample += ',' + ANALOG.voltage; sample += ',' + FC.ANALOG.voltage;
sample += ',' + ANALOG.amperage; sample += ',' + FC.ANALOG.amperage;
sample += ',' + ANALOG.mAhdrawn; sample += ',' + FC.ANALOG.mAhdrawn;
sample += ',' + ANALOG.rssi; sample += ',' + FC.ANALOG.rssi;
break; break;
case 'MSP_RC': case 'MSP_RC':
for (var chan = 0; chan < RC.active_channels; chan++) { for (var chan = 0; chan < FC.RC.active_channels; chan++) {
sample += ',' + RC.channels[chan]; sample += ',' + FC.RC.channels[chan];
} }
break; break;
case 'MSP_MOTOR': case 'MSP_MOTOR':
sample += ',' + MOTOR_DATA; sample += ',' + FC.MOTOR_DATA;
break; break;
case 'MSP_DEBUG': case 'MSP_DEBUG':
sample += ',' + SENSOR_DATA.debug; sample += ',' + FC.SENSOR_DATA.debug;
break; break;
} }
} }

View file

@ -1,5 +1,17 @@
'use strict'; 'use strict';
/*global chrome,GUI,BOARD_ALIGNMENT,TABS,helper,$*/
const path = require('path');
const MSPChainerClass = require('./../js/msp/MSPchainer');
const MSP = require('./../js/msp');
const MSPCodes = require('./../js/msp/MSPCodes');
const mspHelper = require('./../js/msp/MSPHelper');
const mspBalancedInterval = require('./../js/msp_balanced_interval');
const mspQueue = require('./../js/serial_queue');
const FC = require('./../js/fc');
const { GUI, TABS } = require('./../js/gui');
const i18n = require('./../js/localization');
const { mixer } = require('./../js/model');
TABS.magnetometer = {}; TABS.magnetometer = {};
@ -35,9 +47,9 @@ TABS.magnetometer.initialize = function (callback) {
mspHelper.loadMixerConfig, mspHelper.loadMixerConfig,
mspHelper.loadBoardAlignment, mspHelper.loadBoardAlignment,
function (callback) { function (callback) {
self.boardAlignmentConfig.pitch = Math.round(BOARD_ALIGNMENT.pitch / 10); self.boardAlignmentConfig.pitch = Math.round(FC.BOARD_ALIGNMENT.pitch / 10);
self.boardAlignmentConfig.roll = Math.round(BOARD_ALIGNMENT.roll / 10); self.boardAlignmentConfig.roll = Math.round(FC.BOARD_ALIGNMENT.roll / 10);
self.boardAlignmentConfig.yaw = Math.round(BOARD_ALIGNMENT.yaw / 10); self.boardAlignmentConfig.yaw = Math.round(FC.BOARD_ALIGNMENT.yaw / 10);
callback(); callback();
}, },
mspHelper.loadSensorAlignment, mspHelper.loadSensorAlignment,
@ -78,16 +90,16 @@ TABS.magnetometer.initialize = function (callback) {
var saveChain = [ var saveChain = [
function (callback) { function (callback) {
BOARD_ALIGNMENT.pitch = self.boardAlignmentConfig.pitch * 10; FC.BOARD_ALIGNMENT.pitch = self.boardAlignmentConfig.pitch * 10;
BOARD_ALIGNMENT.roll = self.boardAlignmentConfig.roll * 10; FC.BOARD_ALIGNMENT.roll = self.boardAlignmentConfig.roll * 10;
BOARD_ALIGNMENT.yaw = self.boardAlignmentConfig.yaw * 10; FC.BOARD_ALIGNMENT.yaw = self.boardAlignmentConfig.yaw * 10;
callback(); callback();
}, },
mspHelper.saveBoardAlignment, mspHelper.saveBoardAlignment,
// Magnetometer alignment // Magnetometer alignment
function (callback) { function (callback) {
let orientation_mag_e = $('select.magalign'); let orientation_mag_e = $('select.magalign');
SENSOR_ALIGNMENT.align_mag = parseInt(orientation_mag_e.val()); FC.SENSOR_ALIGNMENT.align_mag = parseInt(orientation_mag_e.val());
callback(); callback();
}, },
mspHelper.saveSensorAlignment, mspHelper.saveSensorAlignment,
@ -138,7 +150,7 @@ TABS.magnetometer.initialize = function (callback) {
} }
function load_html() { function load_html() {
GUI.load(path.join(__dirname, "tabs/magnetometer.html"), process_html); GUI.load(path.join(__dirname, "magnetometer.html"), process_html);
} }
function generateRange(min, max, step) { function generateRange(min, max, step) {
@ -214,7 +226,7 @@ TABS.magnetometer.initialize = function (callback) {
function updateMagOrientationWithPreset() { function updateMagOrientationWithPreset() {
if (self.isSavePreset) { if (self.isSavePreset) {
const degrees = getAxisDegreeWithPresetAndBoardOrientation(SENSOR_ALIGNMENT.align_mag); const degrees = getAxisDegreeWithPresetAndBoardOrientation(FC.SENSOR_ALIGNMENT.align_mag);
presetUpdated(degrees); presetUpdated(degrees);
} }
} }
@ -320,12 +332,12 @@ TABS.magnetometer.initialize = function (callback) {
for (let i = 0; i < alignments.length; i++) { for (let i = 0; i < alignments.length; i++) {
self.pageElements.orientation_mag_e.append('<option value="' + (i + 1) + '">' + alignments[i] + '</option>'); self.pageElements.orientation_mag_e.append('<option value="' + (i + 1) + '">' + alignments[i] + '</option>');
} }
self.pageElements.orientation_mag_e.val(SENSOR_ALIGNMENT.align_mag); self.pageElements.orientation_mag_e.val(FC.SENSOR_ALIGNMENT.align_mag);
if (areAnglesZero()) { if (areAnglesZero()) {
//If using a preset, checking if custom values are equal to 0 //If using a preset, checking if custom values are equal to 0
//Update the slider, but don't save the value until they will be not modified. //Update the slider, but don't save the value until they will be not modified.
const degrees = getAxisDegreeWithPresetAndBoardOrientation(SENSOR_ALIGNMENT.align_mag); const degrees = getAxisDegreeWithPresetAndBoardOrientation(FC.SENSOR_ALIGNMENT.align_mag);
presetUpdated(degrees); presetUpdated(degrees);
} }
else { else {
@ -416,13 +428,13 @@ TABS.magnetometer.initialize = function (callback) {
} }
self.pageElements.orientation_mag_e.on('change', function () { self.pageElements.orientation_mag_e.on('change', function () {
SENSOR_ALIGNMENT.align_mag = parseInt($(this).val()); FC.SENSOR_ALIGNMENT.align_mag = parseInt($(this).val());
const degrees = getAxisDegreeWithPresetAndBoardOrientation(SENSOR_ALIGNMENT.align_mag); const degrees = getAxisDegreeWithPresetAndBoardOrientation(FC.SENSOR_ALIGNMENT.align_mag);
presetUpdated(degrees); presetUpdated(degrees);
}); });
self.pageElements.orientation_mag_e.on('mousedown', function () { self.pageElements.orientation_mag_e.on('mousedown', function () {
const degrees = getAxisDegreeWithPresetAndBoardOrientation(SENSOR_ALIGNMENT.align_mag); const degrees = getAxisDegreeWithPresetAndBoardOrientation(FC.SENSOR_ALIGNMENT.align_mag);
presetUpdated(degrees); presetUpdated(degrees);
}); });
@ -512,19 +524,19 @@ TABS.magnetometer.initialize = function (callback) {
}); });
function get_fast_data() { function get_fast_data() {
if (helper.mspQueue.shouldDrop()) { if (mspQueue.shouldDrop()) {
return; return;
} }
MSP.send_message(MSPCodes.MSP_ATTITUDE, false, false, function () { MSP.send_message(MSPCodes.MSP_ATTITUDE, false, false, function () {
self.roll_e.text(i18n.getMessage('initialSetupAttitude', [SENSOR_DATA.kinematics[0]])); self.roll_e.text(i18n.getMessage('initialSetupAttitude', [FC.SENSOR_DATA.kinematics[0]]));
self.pitch_e.text(i18n.getMessage('initialSetupAttitude', [SENSOR_DATA.kinematics[1]])); self.pitch_e.text(i18n.getMessage('initialSetupAttitude', [FC.SENSOR_DATA.kinematics[1]]));
self.heading_e.text(i18n.getMessage('initialSetupAttitude', [SENSOR_DATA.kinematics[2]])); self.heading_e.text(i18n.getMessage('initialSetupAttitude', [FC.SENSOR_DATA.kinematics[2]]));
self.render3D(); self.render3D();
}); });
} }
helper.mspBalancedInterval.add('setup_data_pull_fast', 40, 1, get_fast_data); mspBalancedInterval.add('setup_data_pull_fast', 40, 1, get_fast_data);
GUI.content_ready(callback); GUI.content_ready(callback);
} }
@ -570,12 +582,12 @@ TABS.magnetometer.initialize3D = function () {
// load the model including materials // load the model including materials
if (useWebGlRenderer) { if (useWebGlRenderer) {
if (MIXER_CONFIG.appliedMixerPreset === -1) { if (FC.MIXER_CONFIG.appliedMixerPreset === -1) {
model_file = 'custom'; model_file = 'custom';
GUI_control.prototype.log("<span style='color: red; font-weight: bolder'><strong>" + i18n.getMessage("mixerNotConfigured") + "</strong></span>"); GUI_control.prototype.log("<span style='color: red; font-weight: bolder'><strong>" + i18n.getMessage("mixerNotConfigured") + "</strong></span>");
} }
else { else {
model_file = helper.mixer.getById(MIXER_CONFIG.appliedMixerPreset).model; model_file = mixer.getById(FC.MIXER_CONFIG.appliedMixerPreset).model;
} }
} }
else { else {
@ -622,7 +634,7 @@ TABS.magnetometer.initialize3D = function () {
camera.aspect = wrapper.width() / wrapper.height(); camera.aspect = wrapper.width() / wrapper.height();
camera.updateProjectionMatrix(); camera.updateProjectionMatrix();
this.render3D(); self.render3D();
}; };
$(window).on('resize', this.resize3D); $(window).on('resize', this.resize3D);

View file

@ -1,48 +1,35 @@
'use strict'; 'use strict';
//////////////////////////////////// const path = require('path');
// const ol = require('openlayers');
// global Parameters definition const Store = require('electron-store');
// const store = new Store();
//////////////////////////////////// const { dialog } = require("@electron/remote");
const MSPChainerClass = require('./../js/msp/MSPchainer');
// MultiWii NAV Protocol const mspHelper = require('./../js/msp/MSPHelper');
var MWNP = MWNP || {}; const MSPCodes = require('./../js/msp/MSPCodes');
const MSP = require('./../js/msp');
const mspBalancedInterval = require('./../js/msp_balanced_interval.js');
const mspQueue = require('./../js/serial_queue.js');
const { GUI, TABS } = require('./../js/gui');
const FC = require('./../js/fc');
const CONFIGURATOR = require('./../js/data_storage');
const i18n = require('./../js/localization');
const { globalSettings } = require('./../js/globalSettings');
const MWNP = require('./../js/mwnp');
const Waypoint = require('./../js/waypoint')
const WaypointCollection = require('./../js/waypointCollection');
const Safehome = require('./../js/safehome');
const SafehomeCollection = require('./../js/safehomeCollection');
const { ApproachDirection, FwApproach } = require('./../js/fwApproach');
const FwApproachCollection = require('./../js/fwApproachCollection');
const SerialBackend = require('./../js/serial_backend.js');
const { distanceOnLine, wrap_360, calculate_new_cooridatnes } = require('./../js/helpers');
const Plotly = require('./../js/libraries/plotly-latest.min.js');
var MAX_NEG_FW_LAND_ALT = -2000; // cm var MAX_NEG_FW_LAND_ALT = -2000; // cm
// WayPoint type
MWNP.WPTYPE = {
WAYPOINT: 1,
POSHOLD_UNLIM: 2,
POSHOLD_TIME: 3,
RTH: 4,
SET_POI: 5,
JUMP: 6,
SET_HEAD: 7,
LAND: 8
};
MWNP.P3 = {
ALT_TYPE: 0, // Altitude (alt) : Relative (to home altitude) (0) or Absolute (AMSL) (1).
USER_ACTION_1: 1, // WP Action 1
USER_ACTION_2: 2, // WP Action 2
USER_ACTION_3: 3, // WP Action 3
USER_ACTION_4: 4, // WP Action 4
}
// Reverse WayPoint type dictionary
function swap(dict) {
let rev_dict = {};
for (let key in dict) {
rev_dict[dict[key]] = key;
}
return rev_dict;
}
MWNP.WPTYPE.REV = swap(MWNP.WPTYPE);
// Dictionary of Parameter 1,2,3 definition depending on type of action selected (refer to MWNP.WPTYPE) // Dictionary of Parameter 1,2,3 definition depending on type of action selected (refer to MWNP.WPTYPE)
var dictOfLabelParameterPoint = { var dictOfLabelParameterPoint = {
1: {parameter1: 'Speed (cm/s)', parameter2: '', parameter3: 'Sea level Ref'}, 1: {parameter1: 'Speed (cm/s)', parameter2: '', parameter3: 'Sea level Ref'},
@ -80,7 +67,10 @@ TABS.mission_control.initialize = function (callback) {
let textFeature; let textFeature;
var textGeom; var textGeom;
let isOffline = false; let isOffline = false;
let selectedSafehome;
let rthUpdateInterval = 0; let rthUpdateInterval = 0;
let $safehomeContentBox;
let $waypointOptionsTableBody;
let settings = {speed: 0, alt: 5000, safeRadiusSH: 50, fwApproachAlt: 60, fwLandAlt: 5, maxDistSH: 0, fwApproachLength: 0, fwLoiterRadius: 0, bingDemModel: false}; let settings = {speed: 0, alt: 5000, safeRadiusSH: 50, fwApproachAlt: 60, fwLandAlt: 5, maxDistSH: 0, fwApproachLength: 0, fwLoiterRadius: 0, bingDemModel: false};
if (GUI.active_tab != 'mission_control') { if (GUI.active_tab != 'mission_control') {
@ -116,19 +106,19 @@ TABS.mission_control.initialize = function (callback) {
// FC not connected, load page anyway // FC not connected, load page anyway
loadHtml(); loadHtml();
if (!FW_APPROACH) { if (!FC.FW_APPROACH) {
FW_APPROACH = new FwApproachCollection(); FC.FW_APPROACH = new FwApproachCollection();
} }
if (!SAFEHOMES) { if (!FC.SAFEHOMES) {
SAFEHOMES = new SafehomeCollection(); FC.SAFEHOMES = new SafehomeCollection();
} }
for (let i = 0; i < FW_APPROACH.getMaxFwApproachCount(); i++){ for (let i = 0; i < FC.FW_APPROACH.getMaxFwApproachCount(); i++){
FW_APPROACH.put(new FwApproach(i)); FC.FW_APPROACH.put(new FwApproach(i));
} }
} }
function loadHtml() { function loadHtml() {
GUI.load("tabs/mission_control.html", process_html); GUI.load(path.join(__dirname, "mission_control.html"), process_html);
} }
function process_html() { function process_html() {
@ -145,7 +135,6 @@ TABS.mission_control.initialize = function (callback) {
} }
$safehomeContentBox = $('#SafehomeContentBox'); $safehomeContentBox = $('#SafehomeContentBox');
$waypointOptionsTable = $('.waypointOptionsTable');
$waypointOptionsTableBody = $('#waypointOptionsTableBody'); $waypointOptionsTableBody = $('#waypointOptionsTableBody');
if (typeof require !== "undefined") { if (typeof require !== "undefined") {
@ -154,7 +143,7 @@ TABS.mission_control.initialize = function (callback) {
setTimeout(initMap, 200); setTimeout(initMap, 200);
if (!isOffline) { if (!isOffline) {
setTimeout(() => { setTimeout(() => {
if (SAFEHOMES.safehomeCount() >= 1) { if (FC.SAFEHOMES.safehomeCount() >= 1) {
updateSelectedShAndFwAp(0); updateSelectedShAndFwAp(0);
} else { } else {
selectedSafehome = null; selectedSafehome = null;
@ -189,11 +178,11 @@ TABS.mission_control.initialize = function (callback) {
function update_gpsTrack() { function update_gpsTrack() {
let lat = GPS_DATA.lat / 10000000; let lat = FC.GPS_DATA.lat / 10000000;
let lon = GPS_DATA.lon / 10000000; let lon = FC.GPS_DATA.lon / 10000000;
//Update map //Update map
if (GPS_DATA.fix >= 2) { if (FC.GPS_DATA.fix >= 2) {
if (!cursorInitialized) { if (!cursorInitialized) {
cursorInitialized = true; cursorInitialized = true;
@ -205,7 +194,7 @@ TABS.mission_control.initialize = function (callback) {
anchor: [0.5, 0.5], anchor: [0.5, 0.5],
opacity: 1, opacity: 1,
scale: 0.6, scale: 0.6,
src: 'images/icons/icon_mission_airplane.png' src: './images/icons/icon_mission_airplane.png'
})) }))
}); });
@ -232,7 +221,7 @@ TABS.mission_control.initialize = function (callback) {
anchor: [0.5, 1.0], anchor: [0.5, 1.0],
opacity: 1, opacity: 1,
scale: 0.5, scale: 0.5,
src: '/images/icons/cf_icon_RTH.png' src: './images/icons/cf_icon_RTH.png'
})) }))
}); });
@ -327,23 +316,23 @@ TABS.mission_control.initialize = function (callback) {
breadCrumbLS.setCoordinates(coords); breadCrumbLS.setCoordinates(coords);
} }
curPosStyle.getImage().setRotation((SENSOR_DATA.kinematics[2]/360.0) * 6.28318); curPosStyle.getImage().setRotation((FC.SENSOR_DATA.kinematics[2]/360.0) * 6.28318);
//update data text //update data text
textGeom.setCoordinates(map.getCoordinateFromPixel([0,0])); textGeom.setCoordinates(map.getCoordinateFromPixel([0,0]));
let tmpText = textStyle.getText(); let tmpText = textStyle.getText();
tmpText.setText(' \n' + tmpText.setText(' \n' +
'H: ' + SENSOR_DATA.kinematics[2] + 'H: ' + FC.SENSOR_DATA.kinematics[2] +
'\nAlt: ' + SENSOR_DATA.altitude + '\nAlt: ' + FC.SENSOR_DATA.altitude +
'm\nSpeed: ' + GPS_DATA.speed + 'cm/s\n' + 'm\nSpeed: ' + FC.GPS_DATA.speed + 'cm/s\n' +
'Dist: ' + GPS_DATA.distanceToHome + 'm'); 'Dist: ' + FC.GPS_DATA.distanceToHome + 'm');
//update RTH every 5th GPS update since it really shouldn't change //update RTH every 5th GPS update since it really shouldn't change
if(rthUpdateInterval >= 5) if(rthUpdateInterval >= 5)
{ {
MISSION_PLANNER.bufferPoint.number = -1; //needed to get point 0 which id RTH FC.MISSION_PLANNER.bufferPoint.number = -1; //needed to get point 0 which id RTH
MSP.send_message(MSPCodes.MSP_WP, mspHelper.crunch(MSPCodes.MSP_WP), false, function rth_update() { MSP.send_message(MSPCodes.MSP_WP, mspHelper.crunch(MSPCodes.MSP_WP), false, function rth_update() {
var coord = ol.proj.fromLonLat([MISSION_PLANNER.bufferPoint.lon, MISSION_PLANNER.bufferPoint.lat]); var coord = ol.proj.fromLonLat([FC.MISSION_PLANNER.bufferPoint.lon, FC.MISSION_PLANNER.bufferPoint.lat]);
rthGeo.setCoordinates(coord); rthGeo.setCoordinates(coord);
}); });
rthUpdateInterval = 0; rthUpdateInterval = 0;
@ -358,14 +347,14 @@ TABS.mission_control.initialize = function (callback) {
*/ */
if(!isOffline) if(!isOffline)
{ {
helper.mspBalancedInterval.add('gps_pull', 200, 3, function gps_update() { mspBalancedInterval.add('gps_pull', 200, 3, function gps_update() {
// avoid usage of the GPS commands until a GPS sensor is detected for targets that are compiled without GPS support. // avoid usage of the GPS commands until a GPS sensor is detected for targets that are compiled without GPS support.
if (!have_sensor(CONFIG.activeSensors, 'gps')) { if (!SerialBackend.have_sensor(FC.CONFIG.activeSensors, 'gps')) {
update_gpsTrack(); update_gpsTrack();
return; return;
} }
if (helper.mspQueue.shouldDrop()) { if (mspQueue.shouldDrop()) {
return; return;
} }
@ -434,8 +423,8 @@ TABS.mission_control.initialize = function (callback) {
////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////
// define & init Safehome parameters // define & init Safehome parameters
////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////
//var SAFEHOMES = new SafehomeCollection(); // TO COMMENT FOR RELEASE : DECOMMENT FOR DEBUG //var FC.SAFEHOMES = new SafehomeCollection(); // TO COMMENT FOR RELEASE : DECOMMENT FOR DEBUG
//SAFEHOMES.inflate(); // TO COMMENT FOR RELEASE : DECOMMENT FOR DEBUG //FC.SAFEHOMES.inflate(); // TO COMMENT FOR RELEASE : DECOMMENT FOR DEBUG
//var safehomeRangeRadius = 200; //meters //var safehomeRangeRadius = 200; //meters
//var safehomeSafeRadius = 50; //meters //var safehomeSafeRadius = 50; //meters
@ -465,19 +454,17 @@ TABS.mission_control.initialize = function (callback) {
// //
///////////////////////////////////////////// /////////////////////////////////////////////
function loadSettings() { function loadSettings() {
chrome.storage.local.get('missionPlannerSettings', function (result) { var missionPlannerSettings = store.get('missionPlannerSettings', false);
if (result.missionPlannerSettings) { if (missionPlannerSettings) {
if (!result.missionPlannerSettings.fwApproachLength && settings.fwApproachLength) { if (!missionPlannerSettings.fwApproachLength && settings.fwApproachLength) {
result.missionPlannerSettings.fwApproachLength = settings.fwApproachLength; missionPlannerSettings.fwApproachLength = settings.fwApproachLength;
result.missionPlannerSettings.maxDistSH = settings.maxDistSH; missionPlannerSettings.maxDistSH = settings.maxDistSH;
result.missionPlannerSettings.fwLoiterRadius = settings.fwLoiterRadius; missionPlannerSettings.fwLoiterRadius = settings.fwLoiterRadius;
}
saveSettings();
settings = result.missionPlannerSettings;
} }
saveSettings();
refreshSettings(); settings = missionPlannerSettings;
}); }
refreshSettings();
} }
function saveSettings() { function saveSettings() {
@ -509,7 +496,7 @@ TABS.mission_control.initialize = function (callback) {
function checkApproachAltitude(altitude, isSeaLevelRef, sealevel) { function checkApproachAltitude(altitude, isSeaLevelRef, sealevel) {
if (altitude - (isSeaLevelRef ? sealevel * 100 : 0 ) < 0) { if (altitude - (isSeaLevelRef ? sealevel * 100 : 0 ) < 0) {
alert(chrome.i18n.getMessage('MissionPlannerAltitudeChangeReset')); alert(i18n.getMessage('MissionPlannerAltitudeChangeReset'));
return false; return false;
} }
@ -519,7 +506,7 @@ TABS.mission_control.initialize = function (callback) {
function checkLandingAltitude(altitude, isSeaLevelRef, sealevel) { function checkLandingAltitude(altitude, isSeaLevelRef, sealevel) {
if (altitude - (isSeaLevelRef ? sealevel * 100 : 0 ) < MAX_NEG_FW_LAND_ALT) { if (altitude - (isSeaLevelRef ? sealevel * 100 : 0 ) < MAX_NEG_FW_LAND_ALT) {
alert(chrome.i18n.getMessage('MissionPlannerFwLAndingAltitudeChangeReset')); alert(i18n.getMessage('MissionPlannerFwLAndingAltitudeChangeReset'));
return false; return false;
} }
@ -527,8 +514,8 @@ TABS.mission_control.initialize = function (callback) {
} }
function updateSafehomeInfo(){ function updateSafehomeInfo(){
let freeSamehomes = SAFEHOMES.getMaxSafehomeCount() - SAFEHOMES.safehomeCount() let freeSamehomes = FC.SAFEHOMES.getMaxSafehomeCount() - FC.SAFEHOMES.safehomeCount()
$('#availableSafehomes').text(freeSamehomes + '/' + SAFEHOMES.getMaxSafehomeCount()); $('#availableSafehomes').text(freeSamehomes + '/' + FC.SAFEHOMES.getMaxSafehomeCount());
} }
@ -536,10 +523,10 @@ TABS.mission_control.initialize = function (callback) {
/* /*
* Process safehome on Map * Process safehome on Map
*/ */
SAFEHOMES.get().forEach(safehome => { FC.SAFEHOMES.get().forEach(safehome => {
addFwApproach(safehome.getLonMap(), safehome.getLatMap(), FW_APPROACH.get()[safehome.getNumber()], safehomeMarkers); addFwApproach(safehome.getLonMap(), safehome.getLatMap(), FC.FW_APPROACH.get()[safehome.getNumber()], safehomeMarkers);
}); });
SAFEHOMES.get().forEach(safehome => { FC.SAFEHOMES.get().forEach(safehome => {
addSafehomeCircles(safehome); addSafehomeCircles(safehome);
addSafeHomeMarker(safehome); addSafeHomeMarker(safehome);
}); });
@ -561,7 +548,7 @@ TABS.mission_control.initialize = function (callback) {
anchor: [0.5, 1], anchor: [0.5, 1],
opacity: 1, opacity: 1,
scale: 0.5, scale: 0.5,
src: '/images/icons/cf_icon_safehome' + (safehome.isUsed() ? '_used' : '')+ '.png' src: './images/icons/cf_icon_safehome' + (safehome.isUsed() ? '_used' : '')+ '.png'
})), })),
text: new ol.style.Text(({ text: new ol.style.Text(({
text: String(Number(safehome.getNumber())+1), text: String(Number(safehome.getNumber())+1),
@ -870,7 +857,7 @@ TABS.mission_control.initialize = function (callback) {
anchor: [0.5, 1], anchor: [0.5, 1],
opacity: 1, opacity: 1,
scale: 0.5, scale: 0.5,
src: '/images/icons/cf_icon_home.png' src: './images/icons/cf_icon_home.png'
})), })),
}); });
} }
@ -1277,7 +1264,7 @@ TABS.mission_control.initialize = function (callback) {
} }
} }
if (element.getAction() == MWNP.WPTYPE.LAND) { if (element.getAction() == MWNP.WPTYPE.LAND) {
addFwApproach(element.getLonMap(), element.getLatMap(), FW_APPROACH.get()[SAFEHOMES.getMaxSafehomeCount() + element.getMultiMissionIdx()], lines); addFwApproach(element.getLonMap(), element.getLatMap(), FC.FW_APPROACH.get()[FC.SAFEHOMES.getMaxSafehomeCount() + element.getMultiMissionIdx()], lines);
} }
}); });
//reset text position //reset text position
@ -1329,7 +1316,7 @@ TABS.mission_control.initialize = function (callback) {
featureArrow.setStyle( featureArrow.setStyle(
new ol.style.Style({ new ol.style.Style({
image: new ol.style.Icon({ image: new ol.style.Icon({
src: '/images/icons/cf_icon_arrow.png', src: './images/icons/cf_icon_arrow.png',
scale: 0.3, scale: 0.3,
anchor: [0.5, 0.5], anchor: [0.5, 0.5],
rotateWithView: true, rotateWithView: true,
@ -1433,7 +1420,7 @@ TABS.mission_control.initialize = function (callback) {
} }
const $safehomeBox = $safehomeContentBox.find('.missionPlannerSafehomeBox:last-child'); const $safehomeBox = $safehomeContentBox.find('.missionPlannerSafehomeBox:last-child');
$safehomeBox.find('.spacer_box_title').text(chrome.i18n.getMessage('safehomeEdit') + ' ' + (selectedSafehome.getNumber() + 1)); $safehomeBox.find('.spacer_box_title').text(i18n.getMessage('safehomeEdit') + ' ' + (selectedSafehome.getNumber() + 1));
$('#safehomeLatitude').val(selectedSafehome.getLatMap()); $('#safehomeLatitude').val(selectedSafehome.getLatMap());
$('#safehomeLongitude').val(selectedSafehome.getLonMap()); $('#safehomeLongitude').val(selectedSafehome.getLonMap());
@ -1826,7 +1813,7 @@ TABS.mission_control.initialize = function (callback) {
repaintLine4Waypoints(mission); repaintLine4Waypoints(mission);
} }
else if (tempMarker.kind == "safehome") { else if (tempMarker.kind == "safehome") {
let tmpSafehome = SAFEHOMES.get()[tempMarker.number]; let tmpSafehome = FC.SAFEHOMES.get()[tempMarker.number];
tmpSafehome.setLon(Math.round(coord[0] * 1e7)); tmpSafehome.setLon(Math.round(coord[0] * 1e7));
tmpSafehome.setLat(Math.round(coord[1] * 1e7)); tmpSafehome.setLat(Math.round(coord[1] * 1e7));
@ -1882,7 +1869,7 @@ TABS.mission_control.initialize = function (callback) {
mission.getWaypoint(tempMarker.number).setAlt(returnAltitude); mission.getWaypoint(tempMarker.number).setAlt(returnAltitude);
if (mission.getWaypoint(tempMarker.number).getAction() == MWNP.WPTYPE.LAND) { if (mission.getWaypoint(tempMarker.number).getAction() == MWNP.WPTYPE.LAND) {
let approach = FW_APPROACH.get()[SAFEHOMES.getMaxSafehomeCount() + mission.getWaypoint(tempMarker.number).getMultiMissionIdx()]; let approach = FC.FW_APPROACH.get()[FC.SAFEHOMES.getMaxSafehomeCount() + mission.getWaypoint(tempMarker.number).getMultiMissionIdx()];
if (approach.getIsSeaLevelRef()) { if (approach.getIsSeaLevelRef()) {
if (approach.getElevation() != 0) { if (approach.getElevation() != 0) {
approach.setApproachAltAsl(approach.getApproachAltAsl() - approach.getElevation() + elevationAtWP * 100); approach.setApproachAltAsl(approach.getApproachAltAsl() - approach.getElevation() + elevationAtWP * 100);
@ -1910,8 +1897,8 @@ TABS.mission_control.initialize = function (callback) {
} }
else if (tempMarker.kind == "safehome") { else if (tempMarker.kind == "safehome") {
(async () => { (async () => {
let approach = FW_APPROACH.get()[tempMarker.number]; let approach = FC.FW_APPROACH.get()[tempMarker.number];
let safehome = SAFEHOMES.get()[tempMarker.number]; let safehome = FC.SAFEHOMES.get()[tempMarker.number];
const elevation = await approach.getElevationFromServer(safehome.getLonMap(), safehome.getLatMap(), globalSettings) * 100; const elevation = await approach.getElevationFromServer(safehome.getLonMap(), safehome.getLatMap(), globalSettings) * 100;
$('#safehomeElevation').text(elevation / 100 + " m"); $('#safehomeElevation').text(elevation / 100 + " m");
if (approach.getIsSeaLevelRef()) { if (approach.getIsSeaLevelRef()) {
@ -1929,8 +1916,8 @@ TABS.mission_control.initialize = function (callback) {
return false; return false;
}; };
var lat = (GPS_DATA ? (GPS_DATA.lat / 10000000) : 0); var lat = (FC.GPS_DATA ? (FC.GPS_DATA.lat / 10000000) : 0);
var lon = (GPS_DATA ? (GPS_DATA.lon / 10000000) : 0); var lon = (FC.GPS_DATA ? (FC.GPS_DATA.lon / 10000000) : 0);
let mapLayer; let mapLayer;
let control_list; let control_list;
@ -2045,7 +2032,7 @@ TABS.mission_control.initialize = function (callback) {
$("#editMission").hide(); $("#editMission").hide();
selectedMarker = mission.getWaypoint(tempMarker.number); selectedMarker = mission.getWaypoint(tempMarker.number);
selectedFwApproachWp = FW_APPROACH.get()[SAFEHOMES.getMaxSafehomeCount() + selectedMarker.getMultiMissionIdx()]; selectedFwApproachWp = FC.FW_APPROACH.get()[FC.SAFEHOMES.getMaxSafehomeCount() + selectedMarker.getMultiMissionIdx()];
if (selectedFwApproachWp.getLandHeading1() == 0 && selectedFwApproachWp.getLandHeading1() == 0 && selectedFwApproachWp.getApproachAltAsl() == 0 && selectedFwApproachWp.getLandAltAsl() == 0) { if (selectedFwApproachWp.getLandHeading1() == 0 && selectedFwApproachWp.getLandHeading1() == 0 && selectedFwApproachWp.getApproachAltAsl() == 0 && selectedFwApproachWp.getLandAltAsl() == 0) {
selectedFwApproachWp.setApproachAltAsl(settings.fwApproachAlt * 100); selectedFwApproachWp.setApproachAltAsl(settings.fwApproachAlt * 100);
@ -2143,7 +2130,7 @@ TABS.mission_control.initialize = function (callback) {
} }
else if (selectedFeature && tempMarker.kind == "line" && tempMarker.selection && !disableMarkerEdit) { else if (selectedFeature && tempMarker.kind == "line" && tempMarker.selection && !disableMarkerEdit) {
let tempWpCoord = ol.proj.toLonLat(evt.coordinate); let tempWpCoord = ol.proj.toLonLat(evt.coordinate);
let tempWp = new Waypoint(tempMarker.number, MWNP.WPTYPE.WAYPOINT, Math.round(tempWpCoord[1] * 10000000), Math.round(tempWpCoord[0] * 10000000), alt=Number(settings.alt), p1=Number(settings.speed)); let tempWp = new Waypoint(tempMarker.number, MWNP.WPTYPE.WAYPOINT, Math.round(tempWpCoord[1] * 10000000), Math.round(tempWpCoord[0] * 10000000), Number(settings.alt), Number(settings.speed));
tempWp.setMultiMissionIdx(mission.getWaypoint(0).getMultiMissionIdx()); tempWp.setMultiMissionIdx(mission.getWaypoint(0).getMultiMissionIdx());
if (homeMarkers.length && HOME.getAlt() != "N/A") { if (homeMarkers.length && HOME.getAlt() != "N/A") {
@ -2176,11 +2163,11 @@ TABS.mission_control.initialize = function (callback) {
} }
else if (!disableMarkerEdit) { else if (!disableMarkerEdit) {
let tempWpCoord = ol.proj.toLonLat(evt.coordinate); let tempWpCoord = ol.proj.toLonLat(evt.coordinate);
let tempWp = new Waypoint(mission.get().length, MWNP.WPTYPE.WAYPOINT, Math.round(tempWpCoord[1] * 10000000), Math.round(tempWpCoord[0] * 10000000), alt=Number(settings.alt), p1=Number(settings.speed)); let tempWp = new Waypoint(mission.get().length, MWNP.WPTYPE.WAYPOINT, Math.round(tempWpCoord[1] * 10000000), Math.round(tempWpCoord[0] * 10000000), Number(settings.alt), Number(settings.speed));
if (mission.get().length == 0) { if (mission.get().length == 0) {
tempWp.setMultiMissionIdx(multimissionCount == 0 ? 0 : multimissionCount - 1); tempWp.setMultiMissionIdx(multimissionCount == 0 ? 0 : multimissionCount - 1);
FW_APPROACH.clean(SAFEHOMES.getMaxSafehomeCount() + tempWp.getMultiMissionIdx()); FC.FW_APPROACH.clean(FC.SAFEHOMES.getMaxSafehomeCount() + tempWp.getMultiMissionIdx());
} else { } else {
tempWp.setMultiMissionIdx(mission.getWaypoint(mission.get().length - 1).getMultiMissionIdx()); tempWp.setMultiMissionIdx(mission.getWaypoint(mission.get().length - 1).getMultiMissionIdx());
} }
@ -2237,7 +2224,7 @@ TABS.mission_control.initialize = function (callback) {
////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////
// Update Alt display in meters on ALT field keypress up // Update Alt display in meters on ALT field keypress up
////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////
$('#pointAlt').keyup(function(){ $('#pointAlt').on('keyup', () => {
let altitudeMeters = app.ConvertCentimetersToMeters($(this).val()); let altitudeMeters = app.ConvertCentimetersToMeters($(this).val());
$('#altitudeInMeters').text(` ${altitudeMeters}m`); $('#altitudeInMeters').text(` ${altitudeMeters}m`);
}); });
@ -2332,7 +2319,7 @@ TABS.mission_control.initialize = function (callback) {
let found = false; let found = false;
mission.get().forEach(wp => { mission.get().forEach(wp => {
if (wp.getAction() == MWNP.WPTYPE.LAND) { if (wp.getAction() == MWNP.WPTYPE.LAND) {
alert(chrome.i18n.getMessage('MissionPlannerOnlyOneLandWp')); alert(i18n.getMessage('MissionPlannerOnlyOneLandWp'));
found = true; found = true;
$(event.currentTarget).val(selectedMarker.getAction()); $(event.currentTarget).val(selectedMarker.getAction());
} }
@ -2705,16 +2692,16 @@ TABS.mission_control.initialize = function (callback) {
$('#addSafehome').on('click', () => { $('#addSafehome').on('click', () => {
if (SAFEHOMES.safehomeCount() + 1 > SAFEHOMES.getMaxSafehomeCount()){ if (FC.SAFEHOMES.safehomeCount() + 1 > FC.SAFEHOMES.getMaxSafehomeCount()){
alert(chrome.i18n.getMessage('missionSafehomeMaxSafehomesReached')); alert(i18n.getMessage('missionSafehomeMaxSafehomesReached'));
return; return;
} }
let mapCenter = map.getView().getCenter(); let mapCenter = map.getView().getCenter();
let midLon = Math.round(ol.proj.toLonLat(mapCenter)[0] * 1e7); let midLon = Math.round(ol.proj.toLonLat(mapCenter)[0] * 1e7);
let midLat = Math.round(ol.proj.toLonLat(mapCenter)[1] * 1e7); let midLat = Math.round(ol.proj.toLonLat(mapCenter)[1] * 1e7);
SAFEHOMES.put(new Safehome(SAFEHOMES.safehomeCount(), 1, midLat, midLon)); FC.SAFEHOMES.put(new Safehome(FC.SAFEHOMES.safehomeCount(), 1, midLat, midLon));
updateSelectedShAndFwAp(SAFEHOMES.safehomeCount() - 1); updateSelectedShAndFwAp(FC.SAFEHOMES.safehomeCount() - 1);
renderSafeHomeOptions(); renderSafeHomeOptions();
cleanSafehomeLayers(); cleanSafehomeLayers();
renderSafehomesOnMap(); renderSafehomesOnMap();
@ -2733,7 +2720,7 @@ TABS.mission_control.initialize = function (callback) {
mspHelper.loadSafehomes, mspHelper.loadSafehomes,
mspHelper.loadFwApproach, mspHelper.loadFwApproach,
function() { function() {
if (SAFEHOMES.safehomeCount() >= 1) { if (FC.SAFEHOMES.safehomeCount() >= 1) {
updateSelectedShAndFwAp(0); updateSelectedShAndFwAp(0);
} else { } else {
selectedSafehome = null; selectedSafehome = null;
@ -2743,7 +2730,7 @@ TABS.mission_control.initialize = function (callback) {
cleanSafehomeLayers(); cleanSafehomeLayers();
renderSafehomesOnMap(); renderSafehomesOnMap();
updateSafehomeInfo(); updateSafehomeInfo();
GUI.log(chrome.i18n.getMessage('endGettingSafehomePoints')); GUI.log(i18n.getMessage('endGettingSafehomePoints'));
$('#loadEepromSafehomeButton').removeClass('disabled'); $('#loadEepromSafehomeButton').removeClass('disabled');
} }
]); ]);
@ -2752,7 +2739,7 @@ TABS.mission_control.initialize = function (callback) {
$('#saveEepromSafehomeButton').on('click', function() { $('#saveEepromSafehomeButton').on('click', function() {
$(this).addClass('disabled'); $(this).addClass('disabled');
GUI.log(chrome.i18n.getMessage('startSendingSafehomePoints')); GUI.log(i18n.getMessage('startSendingSafehomePoints'));
var saveChainer = new MSPChainerClass(); var saveChainer = new MSPChainerClass();
saveChainer.setChain([ saveChainer.setChain([
@ -2760,7 +2747,7 @@ TABS.mission_control.initialize = function (callback) {
mspHelper.saveFwApproach, mspHelper.saveFwApproach,
function() { function() {
mspHelper.saveToEeprom(); mspHelper.saveToEeprom();
GUI.log(chrome.i18n.getMessage('endSendingSafehomePoints')); GUI.log(i18n.getMessage('endSendingSafehomePoints'));
$('#saveEepromSafehomeButton').removeClass('disabled'); $('#saveEepromSafehomeButton').removeClass('disabled');
} }
]); ]);
@ -2770,11 +2757,11 @@ TABS.mission_control.initialize = function (callback) {
$('#deleteSafehome').on('click', () => { $('#deleteSafehome').on('click', () => {
if (selectedSafehome && selectedFwApproachSh) { if (selectedSafehome && selectedFwApproachSh) {
var shNum = selectedSafehome.getNumber(); var shNum = selectedSafehome.getNumber();
SAFEHOMES.drop(shNum); FC.SAFEHOMES.drop(shNum);
FW_APPROACH.clean(shNum); FC.FW_APPROACH.clean(shNum);
if (SAFEHOMES.safehomeCount() > 0) { if (FC.SAFEHOMES.safehomeCount() > 0) {
updateSelectedShAndFwAp(SAFEHOMES.safehomeCount() - 1); updateSelectedShAndFwAp(FC.SAFEHOMES.safehomeCount() - 1);
} else { } else {
selectedSafehome = null; selectedSafehome = null;
selectedFwApproachSh = null; selectedFwApproachSh = null;
@ -3028,8 +3015,8 @@ TABS.mission_control.initialize = function (callback) {
removeAllWaypoints(); removeAllWaypoints();
updateMultimissionState(); updateMultimissionState();
} }
for (let i = SAFEHOMES.getMaxSafehomeCount(); i < FW_APPROACH.getMaxFwApproachCount(); i++) { for (let i = FC.SAFEHOMES.getMaxSafehomeCount(); i < FC.FW_APPROACH.getMaxFwApproachCount(); i++) {
FW_APPROACH.clean(i); FC.FW_APPROACH.clean(i);
} }
plotElevation(); plotElevation();
} }
@ -3045,7 +3032,7 @@ TABS.mission_control.initialize = function (callback) {
mission.getAttachedFromWaypoint(selectedMarker).forEach(function (element) { mission.getAttachedFromWaypoint(selectedMarker).forEach(function (element) {
if (element.getAction() == MWNP.WPTYPE.LAND) { if (element.getAction() == MWNP.WPTYPE.LAND) {
FW_APPROACH.clean(element.getNumber()); FC.FW_APPROACH.clean(element.getNumber());
} }
mission.dropWaypoint(element); mission.dropWaypoint(element);
@ -3062,7 +3049,7 @@ TABS.mission_control.initialize = function (callback) {
else { else {
mission.dropWaypoint(selectedMarker); mission.dropWaypoint(selectedMarker);
if (selectedMarker.getAction() == MWNP.WPTYPE.LAND) { if (selectedMarker.getAction() == MWNP.WPTYPE.LAND) {
FW_APPROACH.clean(selectedFwApproachWp.getNumber()); FC.FW_APPROACH.clean(selectedFwApproachWp.getNumber());
} }
selectedMarker = null; selectedMarker = null;
mission.update(singleMissionActive()); mission.update(singleMissionActive());
@ -3184,10 +3171,10 @@ TABS.mission_control.initialize = function (callback) {
///////////////////////////////////////////// /////////////////////////////////////////////
function loadMissionFile(filename) { function loadMissionFile(filename) {
const fs = require('fs'); const fs = require('fs');
if (!window.xml2js) return GUI.log(chrome.i18n.getMessage('errorReadingFileXml2jsNotFound')); if (!window.xml2js) return GUI.log(i18n.getMessage('errorReadingFileXml2jsNotFound'));
for (let i = SAFEHOMES.getMaxSafehomeCount(); i < FW_APPROACH.getMaxFwApproachCount(); i++) { for (let i = FC.SAFEHOMES.getMaxSafehomeCount(); i < FC.FW_APPROACH.getMaxFwApproachCount(); i++) {
FW_APPROACH.clean(i); FC.FW_APPROACH.clean(i);
} }
fs.readFile(filename, (err, data) => { fs.readFile(filename, (err, data) => {
@ -3307,7 +3294,7 @@ TABS.mission_control.initialize = function (callback) {
fwApproach.setIsSeaLevelRef(parseBooleans(node.$[attr]) ? 1 : 0); fwApproach.setIsSeaLevelRef(parseBooleans(node.$[attr]) ? 1 : 0);
} }
} }
FW_APPROACH.insert(fwApproach, SAFEHOMES.getMaxSafehomeCount() + idx); FC.FW_APPROACH.insert(fwApproach, FC.SAFEHOMES.getMaxSafehomeCount() + idx);
} }
} }
} }
@ -3412,8 +3399,8 @@ TABS.mission_control.initialize = function (callback) {
} }
}); });
let approachIdx = 0; let approachIdx = 0;
for (let i = SAFEHOMES.getMaxSafehomeCount(); i < FW_APPROACH.getMaxFwApproachCount(); i++){ for (let i = FC.SAFEHOMES.getMaxSafehomeCount(); i < FC.FW_APPROACH.getMaxFwApproachCount(); i++){
let approach = FW_APPROACH.get()[i]; let approach = FC.FW_APPROACH.get()[i];
if (approach.getLandHeading1() != 0 || approach.getLandHeading2() != 0) { if (approach.getLandHeading1() != 0 || approach.getLandHeading2() != 0) {
var item = { $: { var item = { $: {
'index': approachIdx, 'index': approachIdx,
@ -3446,7 +3433,7 @@ TABS.mission_control.initialize = function (callback) {
///////////////////////////////////////////// /////////////////////////////////////////////
// Load/Save FC mission Toolbox // Load/Save FC mission Toolbox
// mission = configurator store, WP number indexed from 0, MISSION_PLANNER = FC NVM store, WP number indexed from 1 // mission = configurator store, WP number indexed from 0, FC.MISSION_PLANNER = FC NVM store, WP number indexed from 1
///////////////////////////////////////////// /////////////////////////////////////////////
function getWaypointsFromFC(loadEeprom) { function getWaypointsFromFC(loadEeprom) {
@ -3459,19 +3446,19 @@ TABS.mission_control.initialize = function (callback) {
} }
chain.push(mspHelper.loadWaypoints); chain.push(mspHelper.loadWaypoints);
chain.push(function() { chain.push(function() {
GUI.log(chrome.i18n.getMessage('endGetPoint')); GUI.log(i18n.getMessage('endGetPoint'));
if (loadEeprom) { if (loadEeprom) {
GUI.log(chrome.i18n.getMessage('eeprom_load_ok')); GUI.log(i18n.getMessage('eeprom_load_ok'));
$('#loadEepromMissionButton').removeClass('disabled'); $('#loadEepromMissionButton').removeClass('disabled');
} else { } else {
$('#loadMissionButton').removeClass('disabled'); $('#loadMissionButton').removeClass('disabled');
} }
if (!MISSION_PLANNER.getCountBusyPoints()) { if (!FC.MISSION_PLANNER.getCountBusyPoints()) {
alert(chrome.i18n.getMessage('no_waypoints_to_load')); alert(i18n.getMessage('no_waypoints_to_load'));
return; return;
} }
mission.reinit(); mission.reinit();
mission.copy(MISSION_PLANNER); mission.copy(FC.MISSION_PLANNER);
mission.update(false, true); mission.update(false, true);
/* check multimissions */ /* check multimissions */
@ -3499,29 +3486,29 @@ TABS.mission_control.initialize = function (callback) {
} }
function sendWaypointsToFC(saveEeprom) { function sendWaypointsToFC(saveEeprom) {
MISSION_PLANNER.reinit(); FC.MISSION_PLANNER.reinit();
MISSION_PLANNER.copy(mission); FC.MISSION_PLANNER.copy(mission);
MISSION_PLANNER.update(false, true, true); FC.MISSION_PLANNER.update(false, true, true);
let saveChainer = new MSPChainerClass(); let saveChainer = new MSPChainerClass();
saveChainer.setChain([ saveChainer.setChain([
mspHelper.saveWaypoints, mspHelper.saveWaypoints,
mspHelper.saveFwApproach, mspHelper.saveFwApproach,
function () { function () {
GUI.log(chrome.i18n.getMessage('endSendPoint')); GUI.log(i18n.getMessage('endSendPoint'));
if (saveEeprom) { if (saveEeprom) {
$('#saveEepromMissionButton').removeClass('disabled'); $('#saveEepromMissionButton').removeClass('disabled');
GUI.log(chrome.i18n.getMessage('eeprom_saved_ok')); GUI.log(i18n.getMessage('eeprom_saved_ok'));
MSP.send_message(MSPCodes.MSP_WP_MISSION_SAVE, [0], false, setMissionIndex); MSP.send_message(MSPCodes.MSP_WP_MISSION_SAVE, [0], false, setMissionIndex);
} else { } else {
$('#saveMissionButton').removeClass('disabled'); $('#saveMissionButton').removeClass('disabled');
} }
mission.setMaxWaypoints(MISSION_PLANNER.getMaxWaypoints()); mission.setMaxWaypoints(FC.MISSION_PLANNER.getMaxWaypoints());
mission.setValidMission(MISSION_PLANNER.getValidMission()); mission.setValidMission(FC.MISSION_PLANNER.getValidMission());
mission.setCountBusyPoints(MISSION_PLANNER.getCountBusyPoints()); mission.setCountBusyPoints(FC.MISSION_PLANNER.getCountBusyPoints());
multimission.setMaxWaypoints(mission.getMaxWaypoints()); multimission.setMaxWaypoints(mission.getMaxWaypoints());
updateTotalInfo(); updateTotalInfo();
mission.reinit(); mission.reinit();
mission.copy(MISSION_PLANNER); mission.copy(FC.MISSION_PLANNER);
mission.update(false, true); mission.update(false, true);
refreshLayers(); refreshLayers();
$('#MPeditPoint').fadeOut(300); $('#MPeditPoint').fadeOut(300);
@ -3562,8 +3549,8 @@ TABS.mission_control.initialize = function (callback) {
} }
function updateSelectedShAndFwAp(index) { function updateSelectedShAndFwAp(index) {
selectedSafehome = SAFEHOMES.get()[index]; selectedSafehome = FC.SAFEHOMES.get()[index];
selectedFwApproachSh = FW_APPROACH.get()[index]; selectedFwApproachSh = FC.FW_APPROACH.get()[index];
} }
/* resetAltitude = true : For selected WPs only. Changes WP Altitude value back to previous value if setting below ground level. /* resetAltitude = true : For selected WPs only. Changes WP Altitude value back to previous value if setting below ground level.

View file

@ -12,7 +12,7 @@ const i18n = require('./../js/localization');
const { mixer, platform, PLATFORM, INPUT, STABILIZED } = require('./../js/model'); const { mixer, platform, PLATFORM, INPUT, STABILIZED } = require('./../js/model');
const Settings = require('./../js/settings'); const Settings = require('./../js/settings');
const mspBalancedInterval = require('./../js/msp_balanced_interval'); const mspBalancedInterval = require('./../js/msp_balanced_interval');
const jBox = require('../js/libraries/jBox/jBox.min.js') const jBox = require('../js/libraries/jBox/jBox.min.js');
TABS.mixer = {}; TABS.mixer = {};
@ -735,8 +735,8 @@ TABS.mixer.initialize = function (callback, scrollPosition) {
$('#execute-button').on('click', function () { $('#execute-button').on('click', function () {
loadedMixerPresetID = currentMixerPreset.id; loadedMixerPresetID = currentMixerPreset.id;
mixer.loadServoRules(currentMixerPreset); mixer.loadServoRules(FC, currentMixerPreset);
mixer.loadMotorRules(currentMixerPreset); mixer.loadMotorRules(FC, currentMixerPreset);
FC.MIXER_CONFIG.hasFlaps = (currentMixerPreset.hasFlaps === true) ? true : false; FC.MIXER_CONFIG.hasFlaps = (currentMixerPreset.hasFlaps === true) ? true : false;
renderServoMixRules(); renderServoMixRules();
renderMotorMixRules(); renderMotorMixRules();
@ -750,8 +750,8 @@ TABS.mixer.initialize = function (callback, scrollPosition) {
$("#needToUpdateMixerMessage").addClass("is-hidden"); $("#needToUpdateMixerMessage").addClass("is-hidden");
} }
loadedMixerPresetID = currentMixerPreset.id; loadedMixerPresetID = currentMixerPreset.id;
mixer.loadServoRules(currentMixerPreset); mixer.loadServoRules(FC, currentMixerPreset);
mixer.loadMotorRules(currentMixerPreset); mixer.loadMotorRules(FC, currentMixerPreset);
FC.MIXER_CONFIG.hasFlaps = (currentMixerPreset.hasFlaps === true) ? true : false; FC.MIXER_CONFIG.hasFlaps = (currentMixerPreset.hasFlaps === true) ? true : false;
renderServoMixRules(); renderServoMixRules();
renderMotorMixRules(); renderMotorMixRules();
@ -826,7 +826,7 @@ TABS.mixer.initialize = function (callback, scrollPosition) {
function updateRefreshButtonStatus() { function updateRefreshButtonStatus() {
if ( if (
(currentMixerPreset.id != loadedMixerPresetID && helper.mixer.getById(loadedMixerPresetID).platform == PLATFORM.AIRPLANE) || (currentMixerPreset.id != loadedMixerPresetID && mixer.getById(loadedMixerPresetID).platform == PLATFORM.AIRPLANE) ||
(currentMixerPreset.id == loadedMixerPresetID && currentMixerPreset.platform == PLATFORM.AIRPLANE) (currentMixerPreset.id == loadedMixerPresetID && currentMixerPreset.platform == PLATFORM.AIRPLANE)
) { ) {
$("#refresh-mixer-button").parent().removeClass("is-hidden"); $("#refresh-mixer-button").parent().removeClass("is-hidden");

View file

@ -2,6 +2,17 @@
'use strict'; 'use strict';
const path = require('path');
const mspHelper = require('./../js/msp/MSPHelper');
const MSPCodes = require('./../js/msp/MSPCodes');
const MSP = require('./../js/msp');
const { GUI, TABS } = require('./../js/gui');
const FC = require('./../js/fc');
const interval = require('./../js/intervals');
const BitHelper = require('./../js/bitHelper');
const i18n = require('./../js/localization');
TABS.modes = {}; TABS.modes = {};
TABS.modes.initialize = function (callback) { TABS.modes.initialize = function (callback) {
var self = this; var self = this;
@ -23,7 +34,7 @@ TABS.modes.initialize = function (callback) {
} }
function load_html() { function load_html() {
GUI.load(path.join(__dirname, "tabs/modes.html"), process_html); GUI.load(path.join(__dirname, "modes.html"), process_html);
} }
MSP.send_message(MSPCodes.MSP_BOXNAMES, false, false, get_active_box_data); MSP.send_message(MSPCodes.MSP_BOXNAMES, false, false, get_active_box_data);
@ -32,7 +43,7 @@ TABS.modes.initialize = function (callback) {
// generate heads according to RC count // generate heads according to RC count
var table_head = $('table.boxes .heads'); var table_head = $('table.boxes .heads');
var main_head = $('table.boxes .main'); var main_head = $('table.boxes .main');
for (var i = 0; i < (RC.active_channels - 4); i++) { for (var i = 0; i < (FC.RC.active_channels - 4); i++) {
table_head.append('<th colspan="3">AUX ' + (i + 1) + '</th>'); table_head.append('<th colspan="3">AUX ' + (i + 1) + '</th>');
// 3 columns per aux channel (this might be requested to change to 6 in the future, so watch out) // 3 columns per aux channel (this might be requested to change to 6 in the future, so watch out)
@ -47,12 +58,12 @@ TABS.modes.initialize = function (callback) {
i18n.localize();; i18n.localize();;
// generate table from the supplied AUX names and AUX data // generate table from the supplied AUX names and AUX data
for (var i = 0; i < AUX_CONFIG.length; i++) { for (var i = 0; i < FC.AUX_CONFIG.length; i++) {
var line = '<tr class="switches">'; var line = '<tr class="switches">';
line += '<td class="name">' + AUX_CONFIG[i] + '</td>'; line += '<td class="name">' + FC.AUX_CONFIG[i] + '</td>';
for (var j = 0; j < (RC.active_channels - 4) * 3; j++) { for (var j = 0; j < (RC.active_channels - 4) * 3; j++) {
if (bit_check(AUX_CONFIG_values[i], j)) { if (BitHelper.bit_check(FC.AUX_CONFIG_values[i], j)) {
line += '<td><input type="checkbox" checked="checked" /></td>'; line += '<td><input type="checkbox" checked="checked" /></td>';
} else { } else {
line += '<td><input type="checkbox" /></td>'; line += '<td><input type="checkbox" /></td>';
@ -72,14 +83,14 @@ TABS.modes.initialize = function (callback) {
$('.boxes input').each(function () { $('.boxes input').each(function () {
if ($(this).is(':checked')) { if ($(this).is(':checked')) {
AUX_CONFIG_values[main_needle] = bit_set(AUX_CONFIG_values[main_needle], needle); FC.AUX_CONFIG_values[main_needle] = BitHelper.bit_set(FC.AUX_CONFIG_values[main_needle], needle);
} else { } else {
AUX_CONFIG_values[main_needle] = bit_clear(AUX_CONFIG_values[main_needle], needle); FC.AUX_CONFIG_values[main_needle] = BitHelper.bit_clear(FC.AUX_CONFIG_values[main_needle], needle);
} }
needle++; needle++;
if (needle >= (RC.active_channels - 4) * 3) { // 1 aux * 3 checkboxes, 4 AUX = 12 bits per line if (needle >= (FC.RC.active_channels - 4) * 3) { // 1 aux * 3 checkboxes, 4 AUX = 12 bits per line
main_needle++; main_needle++;
needle = 0; needle = 0;
} }
@ -119,21 +130,21 @@ TABS.modes.initialize = function (callback) {
} }
function update_ui() { function update_ui() {
for (var i = 0; i < AUX_CONFIG.length; i++) { for (var i = 0; i < FC.AUX_CONFIG.length; i++) {
if (FC.isModeBitSet(i)) { if (FC.isModeBitSet(i)) {
$('td.name').eq(i).addClass('on').removeClass('off'); $('td.name').eq(i).addClass('on').removeClass('off');
} else { } else {
$('td.name').eq(i).removeClass('on').removeClass('off'); $('td.name').eq(i).removeClass('on').removeClass('off');
if (AUX_CONFIG_values[i] > 0) { if (FC.AUX_CONFIG_values[i] > 0) {
$('td.name').eq(i).addClass('off'); $('td.name').eq(i).addClass('off');
} }
} }
} }
for (var i = 0; i < (RC.active_channels - 4); i++) { for (var i = 0; i < (FC.RC.active_channels - 4); i++) {
box_highlight(i, RC.channels[i + 4]); box_highlight(i, FC.RC.channels[i + 4]);
} }
} }
@ -141,7 +152,7 @@ TABS.modes.initialize = function (callback) {
update_ui(); update_ui();
// enable data pulling // enable data pulling
helper.interval.add('aux_data_pull', get_rc_data, 50); interval.add('aux_data_pull', get_rc_data, 50);
GUI.content_ready(callback); GUI.content_ready(callback);
} }

View file

@ -1,8 +1,17 @@
/*global $,MSP,MSPCodes,TABS,GUI,CONFIGURATOR,helper,mspHelper,SDCARD,chrome*/
'use strict'; 'use strict';
var const path = require('path');
sdcardTimer;
const MSPCodes = require('./../js/msp/MSPCodes');
const MSP = require('./../js/msp');
const { GUI, TABS } = require('./../js/gui');
const FC = require('./../js/fc');
const CONFIGURATOR = require('./../js/data_storage');
const features = require('./../js/feature_framework');
const i18n = require('./../js/localization');
const BitHelper = require('./../js/bitHelper');
var sdcardTimer;
TABS.onboard_logging = { TABS.onboard_logging = {
}; };
@ -67,24 +76,24 @@ TABS.onboard_logging.initialize = function (callback) {
} }
function load_html() { function load_html() {
GUI.load(path.join(__dirname, "tabs/onboard_logging.html"), function() { GUI.load(path.join(__dirname, "onboard_logging.html"), function() {
// translate to user-selected language // translate to user-selected language
i18n.localize();; i18n.localize();;
var var
dataflashPresent = DATAFLASH.totalSize > 0, dataflashPresent = FC.DATAFLASH.totalSize > 0,
blackboxSupport = false; blackboxSupport = false;
if ((BLACKBOX.supported || DATAFLASH.supported) && bit_check(FEATURES, 19)) { if ((FC.BLACKBOX.supported || FC.DATAFLASH.supported) && BitHelper.bit_check(FC.FEATURES, 19)) {
blackboxSupport = true; blackboxSupport = true;
} }
$(".tab-onboard_logging") $(".tab-onboard_logging")
.addClass("serial-supported") .addClass("serial-supported")
.toggleClass("dataflash-supported", DATAFLASH.supported) .toggleClass("dataflash-supported", FC.DATAFLASH.supported)
.toggleClass("dataflash-present", dataflashPresent) .toggleClass("dataflash-present", dataflashPresent)
.toggleClass("sdcard-supported", SDCARD.supported) .toggleClass("sdcard-supported", FC.SDCARD.supported)
.toggleClass("blackbox-config-supported", BLACKBOX.supported) .toggleClass("blackbox-config-supported", FC.BLACKBOX.supported)
.toggleClass("blackbox-supported", blackboxSupport) .toggleClass("blackbox-supported", blackboxSupport)
.toggleClass("blackbox-unsupported", !blackboxSupport); .toggleClass("blackbox-unsupported", !blackboxSupport);
@ -101,22 +110,22 @@ TABS.onboard_logging.initialize = function (callback) {
} }
$('.save-blackbox-feature').on('click', function () { $('.save-blackbox-feature').on('click', function () {
helper.features.reset(); features.reset();
helper.features.fromUI($('.require-blackbox-unsupported')); features.fromUI($('.require-blackbox-unsupported'));
helper.features.execute(save_to_eeprom); features.execute(save_to_eeprom);
}); });
if (BLACKBOX.supported) { if (FC.BLACKBOX.supported) {
$(".tab-onboard_logging a.save-settings").on('click', function () { $(".tab-onboard_logging a.save-settings").on('click', function () {
var rate = $(".blackboxRate select").val().split('/'); var rate = $(".blackboxRate select").val().split('/');
BLACKBOX.blackboxRateNum = parseInt(rate[0], 10); FC.BLACKBOX.blackboxRateNum = parseInt(rate[0], 10);
BLACKBOX.blackboxRateDenom = parseInt(rate[1], 10); FC.BLACKBOX.blackboxRateDenom = parseInt(rate[1], 10);
BLACKBOX.blackboxDevice = parseInt($(".blackboxDevice select").val(), 10); FC.BLACKBOX.blackboxDevice = parseInt($(".blackboxDevice select").val(), 10);
BLACKBOX.blackboxIncludeFlags = getIncludeFlags(); FC.BLACKBOX.blackboxIncludeFlags = getIncludeFlags();
helper.features.reset(); features.reset();
helper.features.fromUI($('.require-blackbox-supported')); features.fromUI($('.require-blackbox-supported'));
helper.features.execute(function () { features.execute(function () {
mspHelper.sendBlackboxConfiguration(save_to_eeprom); mspHelper.sendBlackboxConfiguration(save_to_eeprom);
}); });
}); });
@ -126,7 +135,7 @@ TABS.onboard_logging.initialize = function (callback) {
const blackboxFieldsDiv = $("#blackBoxFlagsDiv"); const blackboxFieldsDiv = $("#blackBoxFlagsDiv");
for (let i = 0; i < blackBoxFields.length; i++) { for (let i = 0; i < blackBoxFields.length; i++) {
const FIELD_ID = blackBoxFields[i]; const FIELD_ID = blackBoxFields[i];
const isEnabled = (BLACKBOX.blackboxIncludeFlags & 1<<i) !==0; const isEnabled = (FC.BLACKBOX.blackboxIncludeFlags & 1<<i) !==0;
const input = $('<input type="checkbox" class="toggle feature" />') const input = $('<input type="checkbox" class="toggle feature" />')
input.attr("id",FIELD_ID); input.attr("id",FIELD_ID);
input.attr("checked",isEnabled); input.attr("checked",isEnabled);
@ -159,20 +168,20 @@ TABS.onboard_logging.initialize = function (callback) {
deviceSelect = $(".blackboxDevice select").empty(); deviceSelect = $(".blackboxDevice select").empty();
deviceSelect.append('<option value="0">Serial port</option>'); deviceSelect.append('<option value="0">Serial port</option>');
if (DATAFLASH.ready) { if (FC.DATAFLASH.ready) {
deviceSelect.append('<option value="1">On-board dataflash chip</option>'); deviceSelect.append('<option value="1">On-board dataflash chip</option>');
} }
if (SDCARD.supported) { if (FC.SDCARD.supported) {
deviceSelect.append('<option value="2">On-board SD card slot</option>'); deviceSelect.append('<option value="2">On-board SD card slot</option>');
} }
deviceSelect.val(BLACKBOX.blackboxDevice); deviceSelect.val(FC.BLACKBOX.blackboxDevice);
} }
function populateLoggingRates() { function populateLoggingRates() {
var var
userRateGCD = gcd(BLACKBOX.blackboxRateNum, BLACKBOX.blackboxRateDenom), userRateGCD = gcd(FC.BLACKBOX.blackboxRateNum, FC.BLACKBOX.blackboxRateDenom),
userRate = {num: BLACKBOX.blackboxRateNum / userRateGCD, denom: BLACKBOX.blackboxRateDenom / userRateGCD}; userRate = {num: FC.BLACKBOX.blackboxRateNum / userRateGCD, denom: FC.BLACKBOX.blackboxRateDenom / userRateGCD};
// Offer a reasonable choice of logging rates (if people want weird steps they can use CLI) // Offer a reasonable choice of logging rates (if people want weird steps they can use CLI)
var var
@ -252,20 +261,20 @@ TABS.onboard_logging.initialize = function (callback) {
} }
function update_html() { function update_html() {
update_bar_width($(".tab-onboard_logging .dataflash-used"), DATAFLASH.usedSize, DATAFLASH.totalSize, "Used space", false); update_bar_width($(".tab-onboard_logging .dataflash-used"), FC.DATAFLASH.usedSize, FC.DATAFLASH.totalSize, "Used space", false);
update_bar_width($(".tab-onboard_logging .dataflash-free"), DATAFLASH.totalSize - DATAFLASH.usedSize, DATAFLASH.totalSize, "Free space", false); update_bar_width($(".tab-onboard_logging .dataflash-free"), FC.DATAFLASH.totalSize - FC.DATAFLASH.usedSize, FC.DATAFLASH.totalSize, "Free space", false);
update_bar_width($(".tab-onboard_logging .sdcard-other"), SDCARD.totalSizeKB - SDCARD.freeSizeKB, SDCARD.totalSizeKB, "Unavailable space", true); update_bar_width($(".tab-onboard_logging .sdcard-other"), FC.SDCARD.totalSizeKB - FC.SDCARD.freeSizeKB, FC.SDCARD.totalSizeKB, "Unavailable space", true);
update_bar_width($(".tab-onboard_logging .sdcard-free"), SDCARD.freeSizeKB, SDCARD.totalSizeKB, "Free space for logs", true); update_bar_width($(".tab-onboard_logging .sdcard-free"), FC.SDCARD.freeSizeKB, FC.SDCARD.totalSizeKB, "Free space for logs", true);
$(".btn a.erase-flash, .btn a.save-flash").toggleClass("disabled", DATAFLASH.usedSize == 0); $(".btn a.erase-flash, .btn a.save-flash").toggleClass("disabled", FC.DATAFLASH.usedSize == 0);
$(".tab-onboard_logging") $(".tab-onboard_logging")
.toggleClass("sdcard-error", SDCARD.state == MSP.SDCARD_STATE_FATAL) .toggleClass("sdcard-error", FC.SDCARD.state == MSP.SDCARD_STATE_FATAL)
.toggleClass("sdcard-initializing", SDCARD.state == MSP.SDCARD_STATE_CARD_INIT || SDCARD.state == MSP.SDCARD_STATE_FS_INIT) .toggleClass("sdcard-initializing", FC.SDCARD.state == MSP.SDCARD_STATE_CARD_INIT || FC.SDCARD.state == MSP.SDCARD_STATE_FS_INIT)
.toggleClass("sdcard-ready", SDCARD.state == MSP.SDCARD_STATE_READY); .toggleClass("sdcard-ready", FC.SDCARD.state == MSP.SDCARD_STATE_READY);
switch (SDCARD.state) { switch (FC.SDCARD.state) {
case MSP.SDCARD_STATE_NOT_PRESENT: case MSP.SDCARD_STATE_NOT_PRESENT:
$(".sdcard-status").text("No card inserted"); $(".sdcard-status").text("No card inserted");
break; break;
@ -282,10 +291,10 @@ TABS.onboard_logging.initialize = function (callback) {
$(".sdcard-status").text("Filesystem starting..."); $(".sdcard-status").text("Filesystem starting...");
break; break;
default: default:
$(".sdcard-status").text("Unknown state " + SDCARD.state); $(".sdcard-status").text("Unknown state " + FC.SDCARD.state);
} }
if (SDCARD.supported && !sdcardTimer) { if (FC.SDCARD.supported && !sdcardTimer) {
// Poll for changes in SD card status // Poll for changes in SD card status
sdcardTimer = setTimeout(function() { sdcardTimer = setTimeout(function() {
sdcardTimer = false; sdcardTimer = false;
@ -343,7 +352,7 @@ TABS.onboard_logging.initialize = function (callback) {
if (GUI.connected_to) { if (GUI.connected_to) {
// Begin by refreshing the occupied size in case it changed while the tab was open // Begin by refreshing the occupied size in case it changed while the tab was open
flash_update_summary(function() { flash_update_summary(function() {
const maxBytes = DATAFLASH.usedSize; const maxBytes = FC.DATAFLASH.usedSize;
prepare_file(function(filename) { prepare_file(function(filename) {
const fs = require('fs'); const fs = require('fs');
@ -415,7 +424,7 @@ TABS.onboard_logging.initialize = function (callback) {
function poll_for_erase_completion() { function poll_for_erase_completion() {
flash_update_summary(function() { flash_update_summary(function() {
if (CONFIGURATOR.connectionValid && !eraseCancelled) { if (CONFIGURATOR.connectionValid && !eraseCancelled) {
if (DATAFLASH.ready) { if (FC.DATAFLASH.ready) {
$(".dataflash-confirm-erase")[0].close(); $(".dataflash-confirm-erase")[0].close();
} else { } else {
setTimeout(poll_for_erase_completion, 500); setTimeout(poll_for_erase_completion, 500);

View file

@ -1,7 +1,24 @@
/*global $*/
'use strict'; 'use strict';
const inflection = require( 'inflection' ); const inflection = require( 'inflection' );
const path = require('path');
const semver = require('semver');
const mapSeries = require('promise-map-series');
const { dialog } = require("@electron/remote");
const Store = require('electron-store');
const store = new Store();
const FC = require('./../js/fc');
const { GUI, TABS } = require('./../js/gui');
const MSP = require('./../js/msp');
const MSPCodes = require('./../js/msp/MSPCodes');
const mspHelper = require('./../js/msp/MSPHelper');
const Settings = require('./../js/settings');
const { globalSettings } = require('./../js/globalSettings');
const { PortHandler } = require('./../js/port_handler');
const i18n = require('./../js/localization');
const jBox = require('./../js/libraries/jBox/jBox.min.js');
var SYM = SYM || {}; var SYM = SYM || {};
SYM.LAST_CHAR = 225; // For drawing the font preview SYM.LAST_CHAR = 225; // For drawing the font preview
@ -2130,7 +2147,7 @@ OSD.is_item_displayed = function(item, group) {
if (typeof group.enabled === 'function' && group.enabled() === false) { if (typeof group.enabled === 'function' && group.enabled() === false) {
return false; return false;
} }
if (item.min_version && !semver.gte(CONFIG.flightControllerVersion, item.min_version)) { if (item.min_version && !semver.gte(FC.CONFIG.flightControllerVersion, item.min_version)) {
return false; return false;
} }
if (typeof item.enabled === 'function' && item.enabled() === false) { if (typeof item.enabled === 'function' && item.enabled() === false) {
@ -2157,7 +2174,7 @@ OSD.reload = function(callback) {
}; };
MSP.promise(MSPCodes.MSP2_CF_SERIAL_CONFIG).then(function (resp) { MSP.promise(MSPCodes.MSP2_CF_SERIAL_CONFIG).then(function (resp) {
$.each(SERIAL_CONFIG.ports, function(index, port){ $.each(FC.SERIAL_CONFIG.ports, function(index, port){
if(port.functions.includes('DJI_FPV')) { if(port.functions.includes('DJI_FPV')) {
OSD.data.isDjiHdFpv = true; OSD.data.isDjiHdFpv = true;
} }
@ -2194,7 +2211,7 @@ OSD.reload = function(callback) {
}); });
}); });
if(semver.gte(CONFIG.flightControllerVersion, '7.1.0')) if(semver.gte(FC.CONFIG.flightControllerVersion, '7.1.0'))
{ {
MSP.send_message(MSPCodes.MSP2_INAV_CUSTOM_OSD_ELEMENTS); MSP.send_message(MSPCodes.MSP2_INAV_CUSTOM_OSD_ELEMENTS);
} }
@ -2613,7 +2630,7 @@ OSD.GUI.updateUnits = function() {
for (var i = 0; i < OSD.constants.UNIT_TYPES.length; i++) { for (var i = 0; i < OSD.constants.UNIT_TYPES.length; i++) {
var unitType = OSD.constants.UNIT_TYPES[i]; var unitType = OSD.constants.UNIT_TYPES[i];
if (unitType.min_version && semver.lt(CONFIG.flightControllerVersion, unitType.min_version)) { if (unitType.min_version && semver.lt(FC.CONFIG.flightControllerVersion, unitType.min_version)) {
continue; continue;
} }
var name = i18n.getMessage(unitType.name); var name = i18n.getMessage(unitType.name);
@ -3180,7 +3197,7 @@ TABS.osd.initialize = function (callback) {
GUI.active_tab = 'osd'; GUI.active_tab = 'osd';
} }
GUI.load(path.join(__dirname, "tabs/osd.html"), Settings.processHtml(function () { GUI.load(path.join(__dirname, "osd.html"), Settings.processHtml(function () {
// translate to user-selected language // translate to user-selected language
i18n.localize(); i18n.localize();
@ -3360,14 +3377,14 @@ TABS.osd.initialize = function (callback) {
// Update RX data for Crossfire detection // Update RX data for Crossfire detection
mspHelper.loadRxConfig(function() { mspHelper.loadRxConfig(function() {
useCRSFRx = (RX_CONFIG.serialrx_provider == 6); useCRSFRx = (FC.RX_CONFIG.serialrx_provider == 6);
}); });
// Get status of ESC Telemetry // Get status of ESC Telemetry
useESCTelemetry = false; useESCTelemetry = false;
MSP.send_message(MSPCodes.MSP2_CF_SERIAL_CONFIG, false, false, function() { MSP.send_message(MSPCodes.MSP2_CF_SERIAL_CONFIG, false, false, function() {
for (var portIndex = 0; portIndex < SERIAL_CONFIG.ports.length; portIndex++) { for (var portIndex = 0; portIndex < FC.SERIAL_CONFIG.ports.length; portIndex++) {
var serialPort = SERIAL_CONFIG.ports[portIndex]; var serialPort = FC.SERIAL_CONFIG.ports[portIndex];
if (serialPort.functions.indexOf("ESC") >= 0) { if (serialPort.functions.indexOf("ESC") >= 0) {
useESCTelemetry = true; useESCTelemetry = true;
break; break;
@ -3378,26 +3395,26 @@ TABS.osd.initialize = function (callback) {
// Update SENSOR_CONFIG, used to detect // Update SENSOR_CONFIG, used to detect
// OSD_AIR_SPEED // OSD_AIR_SPEED
mspHelper.loadSensorConfig(function () { mspHelper.loadSensorConfig(function () {
useBaro = (SENSOR_CONFIG.barometer != 0); useBaro = (FC.SENSOR_CONFIG.barometer != 0);
usePitot = (SENSOR_CONFIG.pitot != 0); usePitot = (FC.SENSOR_CONFIG.pitot != 0);
GUI.content_ready(callback); GUI.content_ready(callback);
}); });
if(semver.gte(CONFIG.flightControllerVersion, '7.1.0')) { if(semver.gte(FC.CONFIG.flightControllerVersion, '7.1.0')) {
mspHelper.loadOsdCustomElements(createCustomElements); mspHelper.loadOsdCustomElements(createCustomElements);
} }
})); }));
}; };
function createCustomElements(){ function createCustomElements(){
if(OSD_CUSTOM_ELEMENTS.settings.customElementsCount == 0){ if(FC.OSD_CUSTOM_ELEMENTS.settings.customElementsCount == 0){
$('.custom-element-container').remove(); $('.custom-element-container').remove();
return; return;
} }
var customElementsContainer = $('#osdCustomElements'); var customElementsContainer = $('#osdCustomElements');
for(var i = 0; i < OSD_CUSTOM_ELEMENTS.settings.customElementsCount; i++){ for(var i = 0; i < FC.OSD_CUSTOM_ELEMENTS.settings.customElementsCount; i++){
var label = $('<label>'); var label = $('<label>');
var customElementTable = $('<table>').addClass('osdCustomElement_main_table'); var customElementTable = $('<table>').addClass('osdCustomElement_main_table');
@ -3420,7 +3437,7 @@ function createCustomElements(){
customElementRowType.append($('<td>').append(select)); customElementRowType.append($('<td>').append(select));
customElementRowValue.append($('<td>').addClass('osdCustomElement-' + i + '-part-' + ii + '-value').append( customElementRowValue.append($('<td>').addClass('osdCustomElement-' + i + '-part-' + ii + '-value').append(
$('<input>').addClass('value').addClass('text').attr('type', 'text').attr('maxlength', OSD_CUSTOM_ELEMENTS.settings.customElementTextSize).hide() $('<input>').addClass('value').addClass('text').attr('type', 'text').attr('maxlength', FC.OSD_CUSTOM_ELEMENTS.settings.customElementTextSize).hide()
).append( ).append(
$('<input>').addClass('value').addClass('ico').attr('min', 1).attr('max', 255).hide() $('<input>').addClass('value').addClass('ico').attr('min', 1).attr('max', 255).hide()
).append( ).append(
@ -3456,7 +3473,7 @@ function createCustomElements(){
valueBlock.find('.' + dataValue).show(); valueBlock.find('.' + dataValue).show();
}); });
customElementLabel.append($('<td>').attr('colspan', 2).append($('<span>').html(chrome.i18n.getMessage("custom_element") + ' ' + (i + 1)))); customElementLabel.append($('<td>').attr('colspan', 2).append($('<span>').html(i18n.getMessage("custom_element") + ' ' + (i + 1))));
customElementTable.append(customElementRowType).append(customElementRowValue).append(customElementLabel); customElementTable.append(customElementRowType).append(customElementRowValue).append(customElementLabel);
label.append(customElementTable); label.append(customElementTable);
@ -3468,38 +3485,38 @@ function createCustomElements(){
} }
function fillCustomElementsValues() { function fillCustomElementsValues() {
for (var i = 0; i < OSD_CUSTOM_ELEMENTS.settings.customElementsCount; i++) { for (var i = 0; i < FC.OSD_CUSTOM_ELEMENTS.settings.customElementsCount; i++) {
for (var ii = 0; ii < 3; ii++) { for (var ii = 0; ii < 3; ii++) {
$('.osdCustomElement-' + i + '-part-' + ii + '-type').val(OSD_CUSTOM_ELEMENTS.items[i].customElementItems[ii].type).trigger('change'); $('.osdCustomElement-' + i + '-part-' + ii + '-type').val(FC.OSD_CUSTOM_ELEMENTS.items[i].customElementItems[ii].type).trigger('change');
var valueCell = $('.osdCustomElement-' + i + '-part-' + ii + '-value'); var valueCell = $('.osdCustomElement-' + i + '-part-' + ii + '-value');
switch (OSD_CUSTOM_ELEMENTS.items[i].customElementItems[ii].type){ switch (FC.OSD_CUSTOM_ELEMENTS .items[i].customElementItems[ii].type){
case 1: case 1:
valueCell.find('.text').val(OSD_CUSTOM_ELEMENTS.items[i].customElementText).trigger('change'); valueCell.find('.text').val(FC.OSD_CUSTOM_ELEMENTS .items[i].customElementText).trigger('change');
break; break;
case 2: case 2:
valueCell.find('.ico').val(OSD_CUSTOM_ELEMENTS.items[i].customElementItems[ii].value).trigger('change'); valueCell.find('.ico').val(FC.OSD_CUSTOM_ELEMENTS .items[i].customElementItems[ii].value).trigger('change');
break; break;
case 3: case 3:
valueCell.find('.ico_gv').val(OSD_CUSTOM_ELEMENTS.items[i].customElementItems[ii].value).trigger('change'); valueCell.find('.ico_gv').val(FC.OSD_CUSTOM_ELEMENTS .items[i].customElementItems[ii].value).trigger('change');
break; break;
case 4: case 4:
case 5: case 5:
case 6: case 6:
case 7: case 7:
valueCell.find('.gv').val(OSD_CUSTOM_ELEMENTS.items[i].customElementItems[ii].value).trigger('change'); valueCell.find('.gv').val(FC.OSD_CUSTOM_ELEMENTS .items[i].customElementItems[ii].value).trigger('change');
break; break;
} }
} }
$('.osdCustomElement-' + i + '-visibility-type').val(OSD_CUSTOM_ELEMENTS.items[i].customElementVisibility.type).trigger('change'); $('.osdCustomElement-' + i + '-visibility-type').val(FC.OSD_CUSTOM_ELEMENTS .items[i].customElementVisibility.type).trigger('change');
var valueVisibilityCell = $('.osdCustomElement-' + i + '-visibility-value'); var valueVisibilityCell = $('.osdCustomElement-' + i + '-visibility-value');
switch (OSD_CUSTOM_ELEMENTS.items[i].customElementVisibility.type){ switch (FC.OSD_CUSTOM_ELEMENTS .items[i].customElementVisibility.type){
case 1: case 1:
valueVisibilityCell.find('.gv').val(OSD_CUSTOM_ELEMENTS.items[i].customElementVisibility.value).trigger('change'); valueVisibilityCell.find('.gv').val(FC.OSD_CUSTOM_ELEMENTS .items[i].customElementVisibility.value).trigger('change');
break; break;
case 2: case 2:
valueVisibilityCell.find('.lc').val(OSD_CUSTOM_ELEMENTS.items[i].customElementVisibility.value).trigger('change'); valueVisibilityCell.find('.lc').val(FC.OSD_CUSTOM_ELEMENTS .items[i].customElementVisibility.value).trigger('change');
break; break;
} }
@ -3613,7 +3630,7 @@ function customElementGetDataForRow(row){
data.push8(parseInt(elementVisibilityType.val())); data.push8(parseInt(elementVisibilityType.val()));
data.push16(visibilityValue); data.push16(visibilityValue);
for(var i = 0; i < OSD_CUSTOM_ELEMENTS.settings.customElementTextSize; i++){ for(var i = 0; i < FC.OSD_CUSTOM_ELEMENTS .settings.customElementTextSize; i++){
if(i < text.length){ if(i < text.length){
data.push8(text.charCodeAt(i)) data.push8(text.charCodeAt(i))
}else{ }else{
@ -3716,7 +3733,7 @@ function updatePanServoPreview() {
} }
// Update the panServoOutput select to be visibly easier to use // Update the panServoOutput select to be visibly easier to use
let servoRules = SERVO_RULES; let servoRules = FC.SERVO_RULES;
$('#panServoOutput option').each(function() { $('#panServoOutput option').each(function() {
let servoIndex = $(this).val(); let servoIndex = $(this).val();

View file

@ -1,6 +1,23 @@
/*global chrome,helper,mspHelper*/
'use strict'; 'use strict';
const path = require('path');
const Store = require('electron-store');
const store = new Store()
const MSPChainerClass = require('./../js/msp/MSPchainer');
const mspHelper = require('./../js/msp/MSPHelper');
const MSPCodes = require('./../js/msp/MSPCodes');
const MSP = require('./../js/msp');
const { GUI, TABS } = require('./../js/gui');
const features = require('./../js/feature_framework');
const tabs = require('./../js/tabs');
const FC = require('./../js/fc');
const Settings = require('./../js/settings');
const i18n = require('./../js/localization');
const { scaleRangeInt } = require('./../js/helpers');
const SerialBackend = require('./../js/serial_backend');
const BitHelper = require('./../js/bitHelper');
TABS.pid_tuning = { TABS.pid_tuning = {
}; };
@ -30,12 +47,12 @@ TABS.pid_tuning.initialize = function (callback) {
} }
function load_html() { function load_html() {
GUI.load(path.join(__dirname, "tabs/pid_tuning.html"), Settings.processHtml(process_html)); GUI.load(path.join(__dirname, "pid_tuning.html"), Settings.processHtml(process_html));
} }
function pid_and_rc_to_form() { function pid_and_rc_to_form() {
// Fill in the data from PIDs array // Fill in the data from FC.PIDs array
var pidNames = FC.getPidNames(); var pidNames = FC.getPidNames();
$('[data-pid-bank-position]').each(function () { $('[data-pid-bank-position]').each(function () {
@ -46,22 +63,22 @@ TABS.pid_tuning.initialize = function (callback) {
$this.find('td:first').text(pidNames[bankPosition]); $this.find('td:first').text(pidNames[bankPosition]);
$this.find('input').each(function (index) { $this.find('input').each(function (index) {
$(this).val(PIDs[bankPosition][index]); $(this).val(FC.PIDs[bankPosition][index]);
}); });
} }
}); });
// Fill in data from RC_tuning object // Fill in data from FC.RC_tuning object
$('#rate-roll').val(RC_tuning.roll_rate); $('#rate-roll').val(FC.RC_tuning.roll_rate);
$('#rate-pitch').val(RC_tuning.pitch_rate); $('#rate-pitch').val(FC.RC_tuning.pitch_rate);
$('#rate-yaw').val(RC_tuning.yaw_rate); $('#rate-yaw').val(FC.RC_tuning.yaw_rate);
$('#rate-manual-roll').val(RC_tuning.manual_roll_rate); $('#rate-manual-roll').val(FC.RC_tuning.manual_roll_rate);
$('#rate-manual-pitch').val(RC_tuning.manual_pitch_rate); $('#rate-manual-pitch').val(FC.RC_tuning.manual_pitch_rate);
$('#rate-manual-yaw').val(RC_tuning.manual_yaw_rate); $('#rate-manual-yaw').val(FC.RC_tuning.manual_yaw_rate);
$('#tpa').val(RC_tuning.dynamic_THR_PID); $('#tpa').val(FC.RC_tuning.dynamic_THR_PID);
$('#tpa-breakpoint').val(RC_tuning.dynamic_THR_breakpoint); $('#tpa-breakpoint').val(FC.RC_tuning.dynamic_THR_breakpoint);
} }
function form_to_pid_and_rc() { function form_to_pid_and_rc() {
@ -75,58 +92,58 @@ TABS.pid_tuning.initialize = function (callback) {
return; return;
} }
if (PIDs[bankPosition]) { if (FC.PIDs[bankPosition]) {
$this.find('input').each(function (index) { $this.find('input').each(function (index) {
PIDs[bankPosition][index] = parseFloat($(this).val()); FC.PIDs[bankPosition][index] = parseFloat($(this).val());
}); });
} }
}); });
// catch RC_tuning changes // catch FC.RC_tuning changes
RC_tuning.roll_rate = parseFloat($('#rate-roll').val()); FC.RC_tuning.roll_rate = parseFloat($('#rate-roll').val());
RC_tuning.pitch_rate = parseFloat($('#rate-pitch').val()); FC.RC_tuning.pitch_rate = parseFloat($('#rate-pitch').val());
RC_tuning.yaw_rate = parseFloat($('#rate-yaw').val()); FC.RC_tuning.yaw_rate = parseFloat($('#rate-yaw').val());
RC_tuning.dynamic_THR_PID = parseInt($('#tpa').val()); FC.RC_tuning.dynamic_THR_PID = parseInt($('#tpa').val());
RC_tuning.dynamic_THR_breakpoint = parseInt($('#tpa-breakpoint').val()); FC.RC_tuning.dynamic_THR_breakpoint = parseInt($('#tpa-breakpoint').val());
RC_tuning.manual_roll_rate = $('#rate-manual-roll').val(); FC.RC_tuning.manual_roll_rate = $('#rate-manual-roll').val();
RC_tuning.manual_pitch_rate = $('#rate-manual-pitch').val(); FC.RC_tuning.manual_pitch_rate = $('#rate-manual-pitch').val();
RC_tuning.manual_yaw_rate = $('#rate-manual-yaw').val(); FC.RC_tuning.manual_yaw_rate = $('#rate-manual-yaw').val();
// Rate Dynamics // Rate Dynamics
RATE_DYNAMICS.sensitivityCenter = parseInt($('#rate_dynamics_center_sensitivity').val()); FC.RATE_DYNAMICS.sensitivityCenter = parseInt($('#rate_dynamics_center_sensitivity').val());
RATE_DYNAMICS.sensitivityEnd = parseInt($('#rate_dynamics_end_sensitivity').val()); FC.RATE_DYNAMICS.sensitivityEnd = parseInt($('#rate_dynamics_end_sensitivity').val());
RATE_DYNAMICS.correctionCenter = parseInt($('#rate_dynamics_center_correction').val()); FC.RATE_DYNAMICS.correctionCenter = parseInt($('#rate_dynamics_center_correction').val());
RATE_DYNAMICS.correctionEnd = parseInt($('#rate_dynamics_end_correction').val()); FC.RATE_DYNAMICS.correctionEnd = parseInt($('#rate_dynamics_end_correction').val());
RATE_DYNAMICS.weightCenter = parseInt($('#rate_dynamics_center_weight').val()); FC.RATE_DYNAMICS.weightCenter = parseInt($('#rate_dynamics_center_weight').val());
RATE_DYNAMICS.weightEnd = parseInt($('#rate_dynamics_end_weight').val()); FC.RATE_DYNAMICS.weightEnd = parseInt($('#rate_dynamics_end_weight').val());
} }
function hideUnusedPids(sensors_detected) { function hideUnusedPids(sensors_detected) {
$('.tab-pid_tuning table.pid_tuning').hide(); $('.tab-pid_tuning table.pid_tuning').hide();
$('#pid_main').show(); $('#pid_main').show();
if (have_sensor(sensors_detected, 'acc')) { if (SerialBackend.have_sensor(sensors_detected, 'acc')) {
$('#pid_accel').show(); $('#pid_accel').show();
} }
if (have_sensor(sensors_detected, 'baro')) { if (SerialBackend.have_sensor(sensors_detected, 'baro')) {
$('#pid_baro').show(); $('#pid_baro').show();
} }
if (have_sensor(sensors_detected, 'mag')) { if (SerialBackend.have_sensor(sensors_detected, 'mag')) {
$('#pid_mag').show(); $('#pid_mag').show();
} }
if (bit_check(FEATURES, 7)) { if (BitHelper.bit_check(FC.FEATURES, 7)) {
$('#pid_gps').show(); $('#pid_gps').show();
} }
if (have_sensor(sensors_detected, 'sonar')) { if (SerialBackend.have_sensor(sensors_detected, 'sonar')) {
$('#pid_baro').show(); $('#pid_baro').show();
} }
} }
function process_html() { function process_html() {
// translate to user-selected language // translate to user-selected language
if (EZ_TUNE.enabled) { if (FC.EZ_TUNE.enabled) {
$("#tuning-wrapper").remove(); $("#tuning-wrapper").remove();
$("#tuning-footer").remove(); $("#tuning-footer").remove();
$('#note-wrapper').show(); $('#note-wrapper').show();
@ -136,10 +153,10 @@ TABS.pid_tuning.initialize = function (callback) {
i18n.localize();; i18n.localize();;
helper.tabs.init($('.tab-pid_tuning')); tabs.init($('.tab-pid_tuning'));
helper.features.updateUI($('.tab-pid_tuning'), FEATURES); features.updateUI($('.tab-pid_tuning'), FC.FEATURES);
hideUnusedPids(CONFIG.activeSensors); hideUnusedPids(FC.CONFIG.activeSensors);
$('#showAllPids').on('click', function(){ $('#showAllPids').on('click', function(){
if($(this).text() == "Show all PIDs") { if($(this).text() == "Show all PIDs") {
@ -147,7 +164,7 @@ TABS.pid_tuning.initialize = function (callback) {
$(this).text('Hide unused PIDs'); $(this).text('Hide unused PIDs');
$('.show').addClass('unusedPIDsHidden'); $('.show').addClass('unusedPIDsHidden');
} else { } else {
hideUnusedPids(CONFIG.activeSensors); hideUnusedPids(FC.CONFIG.activeSensors);
$(this).text('Show all PIDs'); $(this).text('Show all PIDs');
$('.show').removeClass('unusedPIDsHidden'); $('.show').removeClass('unusedPIDsHidden');
} }
@ -157,7 +174,7 @@ TABS.pid_tuning.initialize = function (callback) {
if (confirm(i18n.getMessage('confirm_reset_pid'))) { if (confirm(i18n.getMessage('confirm_reset_pid'))) {
MSP.send_message(MSPCodes.MSP_SET_RESET_CURR_PID, false, false, false); MSP.send_message(MSPCodes.MSP_SET_RESET_CURR_PID, false, false, false);
updateActivatedTab(); GUI.updateActivatedTab();
} }
}); });
@ -215,7 +232,7 @@ TABS.pid_tuning.initialize = function (callback) {
} }
$(this).parent().find('input[name="value-input"]').val(val); $(this).parent().find('input[name="value-input"]').val(val);
PIDs[$(this).parent().data('axis')][$(this).parent().data('bank')] = val; FC.PIDs[$(this).parent().data('axis')][$(this).parent().data('bank')] = val;
}); });
$(".pid-slider-row [name='value-input']").on('change', function () { $(".pid-slider-row [name='value-input']").on('change', function () {
@ -230,7 +247,7 @@ TABS.pid_tuning.initialize = function (callback) {
} }
$(this).parent().find('input[name="value-slider"]').val(newVal); $(this).parent().find('input[name="value-slider"]').val(newVal);
PIDs[$(this).parent().data('axis')][$(this).parent().data('bank')] = $(this).val(); FC.PIDs[$(this).parent().data('axis')][$(this).parent().data('bank')] = $(this).val();
}); });
let axis = 0; let axis = 0;
@ -243,21 +260,21 @@ TABS.pid_tuning.initialize = function (callback) {
let $this = $(this); let $this = $(this);
$this.data('axis', axis); $this.data('axis', axis);
$this.data('bank', bank); $this.data('bank', bank);
$this.find('input[name="value-input"]').val(PIDs[axis][bank]).trigger('change'); $this.find('input[name="value-input"]').val(FC.PIDs[axis][bank]).trigger('change');
bank++; bank++;
}); });
axis++; axis++;
}); });
GUI.sliderize($('#rate_dynamics_center_sensitivity'), RATE_DYNAMICS.sensitivityCenter, 25, 175); GUI.sliderize($('#rate_dynamics_center_sensitivity'), FC.RATE_DYNAMICS.sensitivityCenter, 25, 175);
GUI.sliderize($('#rate_dynamics_end_sensitivity'), RATE_DYNAMICS.sensitivityEnd, 25, 175); GUI.sliderize($('#rate_dynamics_end_sensitivity'), FC.RATE_DYNAMICS.sensitivityEnd, 25, 175);
GUI.sliderize($('#rate_dynamics_center_correction'), RATE_DYNAMICS.correctionCenter, 10, 95); GUI.sliderize($('#rate_dynamics_center_correction'), FC.RATE_DYNAMICS.correctionCenter, 10, 95);
GUI.sliderize($('#rate_dynamics_end_correction'), RATE_DYNAMICS.correctionEnd, 10, 95); GUI.sliderize($('#rate_dynamics_end_correction'), FC.RATE_DYNAMICS.correctionEnd, 10, 95);
GUI.sliderize($('#rate_dynamics_center_weight'), RATE_DYNAMICS.weightCenter, 0, 95); GUI.sliderize($('#rate_dynamics_center_weight'), FC.RATE_DYNAMICS.weightCenter, 0, 95);
GUI.sliderize($('#rate_dynamics_end_weight'), RATE_DYNAMICS.weightEnd, 0, 95); GUI.sliderize($('#rate_dynamics_end_weight'), FC.RATE_DYNAMICS.weightEnd, 0, 95);
if (!FC.isRpyFfComponentUsed()) { if (!FC.isRpyFfComponentUsed()) {
$('.rpy_ff').prop('disabled', 'disabled'); $('.rpy_ff').prop('disabled', 'disabled');
@ -314,9 +331,9 @@ TABS.pid_tuning.initialize = function (callback) {
}); });
} }
helper.features.reset(); features.reset();
helper.features.fromUI($('.tab-pid_tuning')); features.fromUI($('.tab-pid_tuning'));
helper.features.execute(function () { features.execute(function () {
mspHelper.savePidData(send_rc_tuning_changes); mspHelper.savePidData(send_rc_tuning_changes);
}); });
}); });

View file

@ -2,6 +2,14 @@
const path = require('path'); const path = require('path');
const mspHelper = require('./../js/msp/MSPHelper');
const MSPCodes = require('./../js/msp/MSPCodes');
const MSP = require('./../js/msp');
const { GUI, TABS } = require('./../js/gui');
const FC = require('./../js/fc');
const i18n = require('./../js/localization');
const serialPortHelper = require('./../js/serialPortHelper');
TABS.ports = {}; TABS.ports = {};
TABS.ports.initialize = function (callback) { TABS.ports.initialize = function (callback) {
@ -13,7 +21,7 @@ TABS.ports.initialize = function (callback) {
} }
mspHelper.loadSerialPorts(function () { mspHelper.loadSerialPorts(function () {
GUI.load("./tabs/ports.html", on_tab_loaded_handler) GUI.load(path.join(__dirname, "ports.html"), on_tab_loaded_handler)
}); });
function update_ui() { function update_ui() {
@ -24,31 +32,31 @@ TABS.ports.initialize = function (callback) {
$elements; $elements;
$elements = $('select.sensors_baudrate'); $elements = $('select.sensors_baudrate');
for (i = 0; i < helper.serialPortHelper.getBauds('SENSOR').length; i++) { for (i = 0; i < serialPortHelper.getBauds('SENSOR').length; i++) {
$elements.append('<option value="' + helper.serialPortHelper.getBauds('SENSOR')[i] + '">' + helper.serialPortHelper.getBauds('SENSOR')[i] + '</option>'); $elements.append('<option value="' + serialPortHelper.getBauds('SENSOR')[i] + '">' + serialPortHelper.getBauds('SENSOR')[i] + '</option>');
} }
$elements = $('select.msp_baudrate'); $elements = $('select.msp_baudrate');
for (i = 0; i < helper.serialPortHelper.getBauds('MSP').length; i++) { for (i = 0; i < serialPortHelper.getBauds('MSP').length; i++) {
$elements.append('<option value="' + helper.serialPortHelper.getBauds('MSP')[i] + '">' + helper.serialPortHelper.getBauds('MSP')[i] + '</option>'); $elements.append('<option value="' + serialPortHelper.getBauds('MSP')[i] + '">' + serialPortHelper.getBauds('MSP')[i] + '</option>');
} }
$elements = $('select.telemetry_baudrate'); $elements = $('select.telemetry_baudrate');
for (i = 0; i < helper.serialPortHelper.getBauds('TELEMETRY').length; i++) { for (i = 0; i < serialPortHelper.getBauds('TELEMETRY').length; i++) {
$elements.append('<option value="' + helper.serialPortHelper.getBauds('TELEMETRY')[i] + '">' + helper.serialPortHelper.getBauds('TELEMETRY')[i] + '</option>'); $elements.append('<option value="' + serialPortHelper.getBauds('TELEMETRY')[i] + '">' + serialPortHelper.getBauds('TELEMETRY')[i] + '</option>');
} }
$elements = $('select.peripherals_baudrate'); $elements = $('select.peripherals_baudrate');
for (i = 0; i < helper.serialPortHelper.getBauds('PERIPHERAL').length; i++) { for (i = 0; i < serialPortHelper.getBauds('PERIPHERAL').length; i++) {
$elements.append('<option value="' + helper.serialPortHelper.getBauds('PERIPHERAL')[i] + '">' + helper.serialPortHelper.getBauds('PERIPHERAL')[i] + '</option>'); $elements.append('<option value="' + serialPortHelper.getBauds('PERIPHERAL')[i] + '">' + serialPortHelper.getBauds('PERIPHERAL')[i] + '</option>');
} }
var ports_e = $('.tab-ports .ports'); var ports_e = $('.tab-ports .ports');
var port_configuration_template_e = $('#tab-ports-templates .portConfiguration'); var port_configuration_template_e = $('#tab-ports-templates .portConfiguration');
for (var portIndex = 0; portIndex < SERIAL_CONFIG.ports.length; portIndex++) { for (var portIndex = 0; portIndex < FC.SERIAL_CONFIG.ports.length; portIndex++) {
var port_configuration_e = port_configuration_template_e.clone(); var port_configuration_e = port_configuration_template_e.clone();
var serialPort = SERIAL_CONFIG.ports[portIndex]; var serialPort = FC.SERIAL_CONFIG.ports[portIndex];
port_configuration_e.data('serialPort', serialPort); port_configuration_e.data('serialPort', serialPort);
@ -60,7 +68,7 @@ TABS.ports.initialize = function (callback) {
port_configuration_e.find('select.sensors_baudrate').val(serialPort.sensors_baudrate); port_configuration_e.find('select.sensors_baudrate').val(serialPort.sensors_baudrate);
port_configuration_e.find('select.peripherals_baudrate').val(serialPort.peripherals_baudrate); port_configuration_e.find('select.peripherals_baudrate').val(serialPort.peripherals_baudrate);
port_configuration_e.find('.identifier').text(helper.serialPortHelper.getPortName(serialPort.identifier)); port_configuration_e.find('.identifier').text(serialPortHelper.getPortName(serialPort.identifier));
if (serialPort.identifier >= 30) { if (serialPort.identifier >= 30) {
port_configuration_e.find('.softSerialWarning').css("display", "inline") port_configuration_e.find('.softSerialWarning').css("display", "inline")
} else { } else {
@ -77,8 +85,8 @@ TABS.ports.initialize = function (callback) {
let functions_e_id = "portFunc-" + column + "-" + portIndex; let functions_e_id = "portFunc-" + column + "-" + portIndex;
functions_e.attr("id", functions_e_id); functions_e.attr("id", functions_e_id);
for (i = 0; i < helper.serialPortHelper.getRules().length; i++) { for (i = 0; i < serialPortHelper.getRules().length; i++) {
var functionRule = helper.serialPortHelper.getRules()[i]; var functionRule = serialPortHelper.getRules()[i];
var functionName = functionRule.name; var functionName = functionRule.name;
if (functionRule.groups.indexOf(column) == -1) { if (functionRule.groups.indexOf(column) == -1) {
@ -102,9 +110,14 @@ TABS.ports.initialize = function (callback) {
select_e = functions_e.find(selectElementSelector); select_e = functions_e.find(selectElementSelector);
if (select_e.length == 0) { if (select_e.length == 0) {
functions_e.prepend('<span class="function"><select name="' + selectElementName + '" class="function-select ' + selectElementName + '" onchange="updateDefaultBaud(\'' + functions_e_id + '\', \'' + column + '\')" /></span>'); functions_e.prepend('<span class="function"><select id="' + selectElementName + '" name="' + selectElementName + '" class="function-select ' + selectElementName + '" /></span>');
functions_e.find('#' + selectElementName).on('change', () => {
updateDefaultBaud(functions_e_id, column);
});
select_e = functions_e.find(selectElementSelector); select_e = functions_e.find(selectElementSelector);
var disabledText = chrome.i18n.getMessage('portsTelemetryDisabled'); var disabledText = i18n.getMessage('portsTelemetryDisabled');
select_e.append('<option value="">' + disabledText + '</option>'); select_e.append('<option value="">' + disabledText + '</option>');
} }
select_e.append('<option value="' + functionName + '">' + functionRule.displayName + '</option>'); select_e.append('<option value="' + functionName + '">' + functionRule.displayName + '</option>');
@ -128,7 +141,7 @@ TABS.ports.initialize = function (callback) {
let $cT = $(e.currentTarget); let $cT = $(e.currentTarget);
let functionName = $cT.val(); let functionName = $cT.val();
let rule = helper.serialPortHelper.getRuleByName($cT.val()); let rule = serialPortHelper.getRuleByName($cT.val());
//if type is checkbox then process only if selected //if type is checkbox then process only if selected
if ($cT.is('input[type="checkbox"]') && !$cT.is(':checked')) { if ($cT.is('input[type="checkbox"]') && !$cT.is(':checked')) {
@ -177,7 +190,7 @@ TABS.ports.initialize = function (callback) {
function on_save_handler() { function on_save_handler() {
//Clear ports of any previous for serials different than USB VCP //Clear ports of any previous for serials different than USB VCP
SERIAL_CONFIG.ports = SERIAL_CONFIG.ports.filter(item => item.identifier == 20) FC.SERIAL_CONFIG.ports = FC.SERIAL_CONFIG.ports.filter(item => item.identifier == 20)
$('.tab-ports .portConfiguration').each(function () { $('.tab-ports .portConfiguration').each(function () {
@ -216,7 +229,7 @@ TABS.ports.initialize = function (callback) {
peripherals_baudrate: $(portConfiguration_e).find('.peripherals_baudrate').val(), peripherals_baudrate: $(portConfiguration_e).find('.peripherals_baudrate').val(),
identifier: oldSerialPort.identifier identifier: oldSerialPort.identifier
}; };
SERIAL_CONFIG.ports.push(serialPort); FC.SERIAL_CONFIG.ports.push(serialPort);
}); });
mspHelper.saveSerialPorts(save_to_eeprom); mspHelper.saveSerialPorts(save_to_eeprom);
@ -245,7 +258,7 @@ function updateDefaultBaud(baudSelect, column) {
let portName = section.find('.function-' + column).val(); let portName = section.find('.function-' + column).val();
let baudRate = (column === 'telemetry') ? "AUTO" : 115200;; let baudRate = (column === 'telemetry') ? "AUTO" : 115200;;
let rule = helper.serialPortHelper.getRuleByName(portName); let rule = serialPortHelper.getRuleByName(portName);
if (rule && typeof rule.defaultBaud !== 'undefined') { if (rule && typeof rule.defaultBaud !== 'undefined') {
baudRate = rule.defaultBaud; baudRate = rule.defaultBaud;

View file

@ -1,6 +1,16 @@
/*global TABS,MSPChainerClass,mspHelper,GUI,LOGIC_CONDITIONS,PROGRAMMING_PID,GLOBAL_VARIABLES_STATUS,helper,LOGIC_CONDITIONS_STATUS,PROGRAMMING_PID_STATUS*/
'use strict'; 'use strict';
const path = require('path');
const MSPChainerClass = require('./../js/msp/MSPchainer');
const mspBalancedInterval = require('./../js/msp_balanced_interval');
const mspHelper = require('./../js/msp/MSPHelper');
const { GUI, TABS } = require('./../js/gui');
const FC = require('./../js/fc');
const tabs = require('./../js/tabs');
const i18n = require('./../js/localization');
TABS.programming = {}; TABS.programming = {};
TABS.programming.initialize = function (callback, scrollPosition) { TABS.programming.initialize = function (callback, scrollPosition) {
@ -35,28 +45,30 @@ TABS.programming.initialize = function (callback, scrollPosition) {
statusChainer.setExitPoint(onStatusPullDone); statusChainer.setExitPoint(onStatusPullDone);
function loadHtml() { function loadHtml() {
GUI.load(path.join(__dirname, "tabs/programming.html"), processHtml); GUI.load(path.join(__dirname, "programming.html"), processHtml);
} }
function processHtml() { function processHtml() {
LOGIC_CONDITIONS.init($('#subtab-lc')); FC.LOGIC_CONDITIONS.init($('#subtab-lc'));
LOGIC_CONDITIONS.render(); FC.LOGIC_CONDITIONS.render();
GUI.switchery();
PROGRAMMING_PID.init($('#subtab-pid')); FC.PROGRAMMING_PID.init($('#subtab-pid'));
PROGRAMMING_PID.render(); FC.PROGRAMMING_PID.render();
GUI.switchery();
GLOBAL_VARIABLES_STATUS.init($(".gvar__container")); FC.GLOBAL_VARIABLES_STATUS.init($(".gvar__container"));
helper.tabs.init($('.tab-programming')); tabs.init($('.tab-programming'));
i18n.localize();; i18n.localize();;
$('#save-button').on('click', function () { $('#save-button').on('click', function () {
saveChainer.execute(); saveChainer.execute();
GUI.log(i18n.getMessage('programmingEepromSaved')); GUI.log(i18n.getMessage('programmingEepromSaved'));
}); });
helper.mspBalancedInterval.add('logic_conditions_pull', 100, 1, function () { mspBalancedInterval.add('logic_conditions_pull', 100, 1, function () {
statusChainer.execute(); statusChainer.execute();
}); });
@ -64,9 +76,9 @@ TABS.programming.initialize = function (callback, scrollPosition) {
} }
function onStatusPullDone() { function onStatusPullDone() {
LOGIC_CONDITIONS.update(LOGIC_CONDITIONS_STATUS); FC.LOGIC_CONDITIONS.update(FC.LOGIC_CONDITIONS_STATUS);
GLOBAL_VARIABLES_STATUS.update($('.tab-programming')); FC.GLOBAL_VARIABLES_STATUS.update($('.tab-programming'));
PROGRAMMING_PID.update(PROGRAMMING_PID_STATUS); FC.PROGRAMMING_PID.update(FC.PROGRAMMING_PID_STATUS);
} }
} }

View file

@ -1,7 +1,19 @@
/*global chrome*/
'use strict'; 'use strict';
const path = require('path');
const MSPChainerClass = require('./../js/msp/MSPchainer');
const mspHelper = require('./../js/msp/MSPHelper');
const mspQueue = require('./../js/serial_queue');
const mspBalancedInterval = require('./../js/msp_balanced_interval');
const MSPCodes = require('./../js/msp/MSPCodes');
const MSP = require('./../js/msp');
const { GUI, TABS } = require('./../js/gui');
const FC = require('./../js/fc');
const CONFIGURATOR = require('./../js/data_storage');
const Settings = require('./../js/settings');
const i18n = require('./../js/localization');
TABS.receiver = { TABS.receiver = {
rateChartHeight: 117 rateChartHeight: 117
}; };
@ -29,7 +41,7 @@ TABS.receiver.initialize = function (callback) {
loadChainer.execute(); loadChainer.execute();
function load_html() { function load_html() {
GUI.load(path.join(__dirname, "tabs/receiver.html"), Settings.processHtml(process_html)); GUI.load(path.join(__dirname, "receiver.html"), Settings.processHtml(process_html));
} }
function saveSettings(onComplete) { function saveSettings(onComplete) {
@ -106,17 +118,17 @@ TABS.receiver.initialize = function (callback) {
$receiverMode.trigger("change"); $receiverMode.trigger("change");
// fill in data from RC_tuning // fill in data from RC_tuning
$('.tunings .throttle input[name="mid"]').val(RC_tuning.throttle_MID.toFixed(2)); $('.tunings .throttle input[name="mid"]').val(FC.RC_tuning.throttle_MID.toFixed(2));
$('.tunings .throttle input[name="expo"]').val(RC_tuning.throttle_EXPO.toFixed(2)); $('.tunings .throttle input[name="expo"]').val(FC.RC_tuning.throttle_EXPO.toFixed(2));
$('.tunings .rate input[name="expo"]').val(RC_tuning.RC_EXPO.toFixed(2)); $('.tunings .rate input[name="expo"]').val(FC.RC_tuning.RC_EXPO.toFixed(2));
$('.tunings .yaw_rate input[name="yaw_expo"]').val(RC_tuning.RC_YAW_EXPO.toFixed(2)); $('.tunings .yaw_rate input[name="yaw_expo"]').val(FC.RC_tuning.RC_YAW_EXPO.toFixed(2));
$('.tunings .rate input[name="manual_expo"]').val(RC_tuning.manual_RC_EXPO.toFixed(2)); $('.tunings .rate input[name="manual_expo"]').val(FC.RC_tuning.manual_RC_EXPO.toFixed(2));
$('.tunings .yaw_rate input[name="manual_yaw_expo"]').val(RC_tuning.manual_RC_YAW_EXPO.toFixed(2)); $('.tunings .yaw_rate input[name="manual_yaw_expo"]').val(FC.RC_tuning.manual_RC_YAW_EXPO.toFixed(2));
$('.deadband input[name="yaw_deadband"]').val(RC_deadband.yaw_deadband); $('.deadband input[name="yaw_deadband"]').val(FC.RC_deadband.yaw_deadband);
$('.deadband input[name="deadband"]').val(RC_deadband.deadband); $('.deadband input[name="deadband"]').val(FC.RC_deadband.deadband);
// generate bars // generate bars
var bar_names = [ var bar_names = [
@ -127,7 +139,7 @@ TABS.receiver.initialize = function (callback) {
], ],
bar_container = $('.tab-receiver .bars'); bar_container = $('.tab-receiver .bars');
for (var i = 0; i < RC.active_channels; i++) { for (var i = 0; i < FC.RC.active_channels; i++) {
var name; var name;
if (i < bar_names.length) { if (i < bar_names.length) {
name = bar_names[i]; name = bar_names[i];
@ -181,8 +193,8 @@ TABS.receiver.initialize = function (callback) {
// handle rcmap & rssi aux channel // handle rcmap & rssi aux channel
var strBuffer = [], rcMapLetters = FC.getRcMapLetters(); var strBuffer = [], rcMapLetters = FC.getRcMapLetters();
for (var i = 0; i < RC_MAP.length; i++) { for (var i = 0; i < FC.RC_MAP.length; i++) {
strBuffer[RC_MAP[i]] = rcMapLetters[i]; strBuffer[FC.RC_MAP[i]] = rcMapLetters[i];
} }
// reconstruct // reconstruct
@ -223,11 +235,11 @@ TABS.receiver.initialize = function (callback) {
// rssi // rssi
var rssi_channel_e = $('select[name="rssi_channel"]'); var rssi_channel_e = $('select[name="rssi_channel"]');
rssi_channel_e.append('<option value="0">Disabled</option>'); rssi_channel_e.append('<option value="0">Disabled</option>');
for (var i = 5; i < RC.active_channels + 1; i++) { for (var i = 5; i < FC.RC.active_channels + 1; i++) {
rssi_channel_e.append('<option value="' + i + '">CH' + i + '</option>'); rssi_channel_e.append('<option value="' + i + '">CH' + i + '</option>');
} }
$('select[name="rssi_channel"]').val(MISC.rssi_channel); $('select[name="rssi_channel"]').val(FC.MISC.rssi_channel);
var rateHeight = TABS.receiver.rateChartHeight; var rateHeight = TABS.receiver.rateChartHeight;
@ -281,29 +293,29 @@ TABS.receiver.initialize = function (callback) {
$('a.update').on('click', function () { $('a.update').on('click', function () {
// catch RC_tuning changes // catch RC_tuning changes
RC_tuning.throttle_MID = parseFloat($('.tunings .throttle input[name="mid"]').val()); FC.RC_tuning.throttle_MID = parseFloat($('.tunings .throttle input[name="mid"]').val());
RC_tuning.throttle_EXPO = parseFloat($('.tunings .throttle input[name="expo"]').val()); FC.RC_tuning.throttle_EXPO = parseFloat($('.tunings .throttle input[name="expo"]').val());
RC_tuning.RC_EXPO = parseFloat($('.tunings .rate input[name="expo"]').val()); FC.RC_tuning.RC_EXPO = parseFloat($('.tunings .rate input[name="expo"]').val());
RC_tuning.RC_YAW_EXPO = parseFloat($('.tunings .yaw_rate input[name="yaw_expo"]').val()); FC.RC_tuning.RC_YAW_EXPO = parseFloat($('.tunings .yaw_rate input[name="yaw_expo"]').val());
RC_tuning.manual_RC_EXPO = parseFloat($('.tunings .rate input[name="manual_expo"]').val()); FC.RC_tuning.manual_RC_EXPO = parseFloat($('.tunings .rate input[name="manual_expo"]').val());
RC_tuning.manual_RC_YAW_EXPO = parseFloat($('.tunings .yaw_rate input[name="manual_yaw_expo"]').val()); FC.RC_tuning.manual_RC_YAW_EXPO = parseFloat($('.tunings .yaw_rate input[name="manual_yaw_expo"]').val());
RC_deadband.yaw_deadband = parseInt($('.deadband input[name="yaw_deadband"]').val()); FC.RC_deadband.yaw_deadband = parseInt($('.deadband input[name="yaw_deadband"]').val());
RC_deadband.deadband = parseInt($('.deadband input[name="deadband"]').val()); FC.RC_deadband.deadband = parseInt($('.deadband input[name="deadband"]').val());
// catch rc map // catch rc map
var rcMapValue = $('input[name="rcmap"]').val(); var rcMapValue = $('input[name="rcmap"]').val();
var strBuffer = rcMapValue.split(''); var strBuffer = rcMapValue.split('');
for (var i = 0; i < RC_MAP.length; i++) { for (var i = 0; i < FC.RC_MAP.length; i++) {
RC_MAP[i] = strBuffer.indexOf(FC.getRcMapLetters()[i]); FC.RC_MAP[i] = strBuffer.indexOf(FC.getRcMapLetters()[i]);
} }
// catch rssi aux // catch rssi aux
MISC.rssi_channel = parseInt($('select[name="rssi_channel"]').val()); FC.MISC.rssi_channel = parseInt($('select[name="rssi_channel"]').val());
function save_rc_map() { function save_rc_map() {
MSP.send_message(MSPCodes.MSP_SET_RX_MAP, mspHelper.crunch(MSPCodes.MSP_SET_RX_MAP), false, save_misc); MSP.send_message(MSPCodes.MSP_SET_RX_MAP, mspHelper.crunch(MSPCodes.MSP_SET_RX_MAP), false, save_misc);
@ -338,7 +350,7 @@ TABS.receiver.initialize = function (callback) {
}); });
$("a.sticks").on('click', function () { $("a.sticks").on('click', function () {
var mspWin = window.open("tabs/receiver_msp.html", "receiver_msp", "width=420,height=720,menubar=no,contextIsolation=no,nodeIntegration=yes"); var mspWin = window.open("tabs/receiver_msp.html", "receiver_msp", "width=420,height=760,menubar=no,contextIsolation=no,nodeIntegration=yes");
mspWin.window.setRawRx = function (channels) { mspWin.window.setRawRx = function (channels) {
if (CONFIGURATOR.connectionValid && GUI.active_tab != 'cli') { if (CONFIGURATOR.connectionValid && GUI.active_tab != 'cli') {
@ -362,7 +374,7 @@ TABS.receiver.initialize = function (callback) {
/* /*
* Throttling * Throttling
*/ */
if (helper.mspQueue.shouldDrop()) { if (mspQueue.shouldDrop()) {
update_ui(); update_ui();
return; return;
} }
@ -374,14 +386,14 @@ TABS.receiver.initialize = function (callback) {
var i; var i;
// update bars with latest data // update bars with latest data
for (let i = 0; i < RC.active_channels; i++) { for (let i = 0; i < FC.RC.active_channels; i++) {
meter_fill_array[i].css('width', ((RC.channels[i] - meter_scale.min) / (meter_scale.max - meter_scale.min) * 100).clamp(0, 100) + '%'); meter_fill_array[i].css('width', ((FC.RC.channels[i] - meter_scale.min) / (meter_scale.max - meter_scale.min) * 100).clamp(0, 100) + '%');
meter_label_array[i].text(RC.channels[i]); meter_label_array[i].text(FC.RC.channels[i]);
} }
} }
helper.mspBalancedInterval.add('receiver_pull', 35, 1, get_rc_data); mspBalancedInterval.add('receiver_pull', 35, 1, get_rc_data);
GUI.content_ready(callback); GUI.content_ready(callback);
} }

View file

@ -1,7 +1,5 @@
<html> <html>
<head> <head>
<script type="text/javascript" src="../js/i18n.js"></script>
<script type="text/javascript" src="../tabs/receiver_msp.js"></script> <script type="text/javascript" src="../tabs/receiver_msp.js"></script>
<script type="text/javascript" src="../js/libraries/jquery.nouislider.all.min.js"></script> <script type="text/javascript" src="../js/libraries/jquery.nouislider.all.min.js"></script>
<link type="text/css" rel="stylesheet" href="../src/css/receiver-msp.css" media="all" /> <link type="text/css" rel="stylesheet" href="../src/css/receiver-msp.css" media="all" />

View file

@ -1,7 +1,6 @@
"use strict"; "use strict";
window.$ = window.jQuery = require('jquery'); window.$ = window.jQuery = require('jquery');
//const { i18n } = require('.js/i18n.js');
var var
CHANNEL_MIN_VALUE = 1000, CHANNEL_MIN_VALUE = 1000,
@ -121,19 +120,19 @@ function localizeAxisNames() {
var var
gimbal = gimbalElems.get(gimbalIndex); gimbal = gimbalElems.get(gimbalIndex);
// $(".gimbal-label-vert", gimbal).text(i18n.getMessage("controlAxis" + gimbals[gimbalIndex][0])); $(".gimbal-label-vert", gimbal).text(gimbals[gimbalIndex][0]);
// $(".gimbal-label-horz", gimbal).text(i18n.getMessage("controlAxis" + gimbals[gimbalIndex][1])); $(".gimbal-label-horz", gimbal).text(gimbals[gimbalIndex][1]);
} }
for (var sliderIndex = 0; sliderIndex < 8; sliderIndex++) { for (var sliderIndex = 0; sliderIndex < 8; sliderIndex++) {
// $(".slider-label", sliderElems.get(sliderIndex)).text(i18n.getMessage("radioChannelShort") + (sliderIndex + 5)); $(".slider-label", sliderElems.get(sliderIndex)).text("CH " + (sliderIndex + 5));
} }
} }
$(document).ready(function() { $(function() {
$("a.button-enable").on('click', function () { $("a.button-enable").on('click', function () {
var shrinkHeight = $(".warning").height(); var shrinkHeight = $(".warning").height();
$(".warning").slideUp("short", function() { $(".warning").slideUp("short", function() {

View file

@ -1,5 +1,19 @@
'use strict'; 'use strict';
const path = require('path');
const Store = require('electron-store');
const store = new Store();
const MSPCodes = require('./../js/msp/MSPCodes');
const MSP = require('./../js/msp');
const mspQueue = require('./../js/serial_queue');
const { GUI, TABS } = require('./../js/gui');
const FC = require('./../js/fc');
const CONFIGURATOR = require('./../js/data_storage');
const interval = require('./../js/intervals');
const i18n = require('./../js/localization');
const BitHelper = require('./../js/bitHelper');
TABS.sensors = {}; TABS.sensors = {};
TABS.sensors.initialize = function (callback) { TABS.sensors.initialize = function (callback) {
var self = this; var self = this;
@ -10,14 +24,14 @@ TABS.sensors.initialize = function (callback) {
function initSensorData(){ function initSensorData(){
for (var i = 0; i < 3; i++) { for (var i = 0; i < 3; i++) {
SENSOR_DATA.accelerometer[i] = 0; FC.SENSOR_DATA.accelerometer[i] = 0;
SENSOR_DATA.gyroscope[i] = 0; FC.SENSOR_DATA.gyroscope[i] = 0;
SENSOR_DATA.magnetometer[i] = 0; FC.SENSOR_DATA.magnetometer[i] = 0;
SENSOR_DATA.sonar = 0; FC.SENSOR_DATA.sonar = 0;
SENSOR_DATA.air_speed = 0; FC.SENSOR_DATA.air_speed = 0;
SENSOR_DATA.altitude = 0; FC.SENSOR_DATA.altitude = 0;
SENSOR_DATA.temperature[i] = 0; FC.SENSOR_DATA.temperature[i] = 0;
SENSOR_DATA.debug[i] = 0; FC.SENSOR_DATA.debug[i] = 0;
} }
} }
@ -197,24 +211,24 @@ TABS.sensors.initialize = function (callback) {
} }
} }
GUI.load(path.join(__dirname, "tabs/sensors.html"), function load_html() { GUI.load(path.join(__dirname, "sensors.html"), function load_html() {
// translate to user-selected language // translate to user-selected language
i18n.localize();; i18n.localize();;
// disable graphs for sensors that are missing // disable graphs for sensors that are missing
var checkboxes = $('.tab-sensors .info .checkboxes input'); var checkboxes = $('.tab-sensors .info .checkboxes input');
if (!bit_check(CONFIG.activeSensors, 2)) { // mag if (!BitHelper.bit_check(FC.CONFIG.activeSensors, 2)) { // mag
checkboxes.eq(2).prop('disabled', true); checkboxes.eq(2).prop('disabled', true);
} }
if (!bit_check(CONFIG.activeSensors, 4)) { // sonar if (!BitHelper.bit_check(FC.CONFIG.activeSensors, 4)) { // sonar
checkboxes.eq(4).prop('disabled', true); checkboxes.eq(4).prop('disabled', true);
} }
if (!bit_check(CONFIG.activeSensors, 6)) { // airspeed if (!BitHelper.bit_check(FC.CONFIG.activeSensors, 6)) { // airspeed
checkboxes.eq(5).prop('disabled', true); checkboxes.eq(5).prop('disabled', true);
} }
if (!bit_check(CONFIG.activeSensors, 7)) { if (!BitHelper.bit_check(FC.CONFIG.activeSensors, 7)) {
checkboxes.eq(6).prop('disabled', true); checkboxes.eq(6).prop('disabled', true);
} }
@ -254,21 +268,21 @@ TABS.sensors.initialize = function (callback) {
checkboxes.push($(this).prop('checked')); checkboxes.push($(this).prop('checked'));
}); });
$('.tab-sensors .rate select:first').trigger('change'); startPolling();
store.set('graphs_enabled', checkboxes); store.set('graphs_enabled', checkboxes);
}); });
store.get('graphs_enabled', function (result) { var graphs_enabled = store.get('graphs_enabled', false);
if (result.graphs_enabled) { if (graphs_enabled) {
var checkboxes = $('.tab-sensors .info .checkboxes input'); var checkboxes = $('.tab-sensors .info .checkboxes input');
for (var i = 0; i < result.graphs_enabled.length; i++) { for (var i = 0; i < graphs_enabled.length; i++) {
checkboxes.eq(i).not(':disabled').prop('checked', result.graphs_enabled[i]).trigger('change'); checkboxes.eq(i).not(':disabled').prop('checked', graphs_enabled[i]).trigger('change');
}
} else {
$('.tab-sensors .info input:lt(4):not(:disabled)').prop('checked', true).trigger('change');
} }
}); } else {
$('.tab-sensors .info input:lt(4):not(:disabled)').prop('checked', true).trigger('change');
}
// Always start with default/empty sensor data array, clean slate all // Always start with default/empty sensor data array, clean slate all
initSensorData(); initSensorData();
@ -372,14 +386,18 @@ TABS.sensors.initialize = function (callback) {
$('.tab-sensors select[name="debug_refresh_rate"]').val(sensor_settings.rates.debug); $('.tab-sensors select[name="debug_refresh_rate"]').val(sensor_settings.rates.debug);
// start polling data by triggering refresh rate change event // start polling data by triggering refresh rate change event
$('.tab-sensors .rate select:first').trigger('change'); startPolling();
} else { } else {
// start polling immediatly (as there is no configuration saved in the storage) // start polling immediatly (as there is no configuration saved in the storage)
$('.tab-sensors .rate select:first').trigger('change'); startPolling();
} }
$('.tab-sensors .rate select, .tab-sensors .scale select').on('change', function () { $('.tab-sensors .rate select, .tab-sensors .scale select').on('change', function () {
startPolling();
});
function startPolling() {
// if any of the select fields change value, all of the select values are grabbed // if any of the select fields change value, all of the select values are grabbed
// and timers are re-initialized with the new settings // and timers are re-initialized with the new settings
var rates = { var rates = {
@ -419,16 +437,16 @@ TABS.sensors.initialize = function (callback) {
}); });
// timer initialization // timer initialization
helper.interval.killAll(['status_pull', 'global_data_refresh', 'msp-load-update']); interval.killAll(['status_pull', 'global_data_refresh', 'msp-load-update']);
// data pulling timers // data pulling timers
if (checkboxes[0] || checkboxes[1] || checkboxes[2]) { if (checkboxes[0] || checkboxes[1] || checkboxes[2]) {
helper.interval.add('IMU_pull', function () { interval.add('IMU_pull', function () {
/* /*
* Enable balancer * Enable balancer
*/ */
if (helper.mspQueue.shouldDrop()) { if (mspQueue.shouldDrop()) {
update_imu_graphs(); update_imu_graphs();
return; return;
} }
@ -438,12 +456,12 @@ TABS.sensors.initialize = function (callback) {
} }
if (checkboxes[3]) { if (checkboxes[3]) {
helper.interval.add('altitude_pull', function altitude_data_pull() { interval.add('altitude_pull', function altitude_data_pull() {
/* /*
* Enable balancer * Enable balancer
*/ */
if (helper.mspQueue.shouldDrop()) { if (mspQueue.shouldDrop()) {
update_altitude_graph(); update_altitude_graph();
return; return;
} }
@ -453,12 +471,12 @@ TABS.sensors.initialize = function (callback) {
} }
if (checkboxes[4]) { if (checkboxes[4]) {
helper.interval.add('sonar_pull', function sonar_data_pull() { interval.add('sonar_pull', function sonar_data_pull() {
/* /*
* Enable balancer * Enable balancer
*/ */
if (helper.mspQueue.shouldDrop()) { if (mspQueue.shouldDrop()) {
update_sonar_graphs(); update_sonar_graphs();
return; return;
} }
@ -468,12 +486,12 @@ TABS.sensors.initialize = function (callback) {
} }
if (checkboxes[5]) { if (checkboxes[5]) {
helper.interval.add('airspeed_pull', function airspeed_data_pull() { interval.add('airspeed_pull', function airspeed_data_pull() {
/* /*
* Enable balancer * Enable balancer
*/ */
if (helper.mspQueue.shouldDrop()) { if (mspQueue.shouldDrop()) {
update_airspeed_graphs(); update_airspeed_graphs();
return; return;
} }
@ -483,12 +501,12 @@ TABS.sensors.initialize = function (callback) {
} }
if (checkboxes[6]) { if (checkboxes[6]) {
helper.interval.add('temperature_pull', function temperature_data_pull() { interval.add('temperature_pull', function temperature_data_pull() {
/* /*
* Enable balancer * Enable balancer
*/ */
if (helper.mspQueue.shouldDrop()) { if (mspQueue.shouldDrop()) {
update_temperature_graphs(); update_temperature_graphs();
return; return;
} }
@ -498,12 +516,12 @@ TABS.sensors.initialize = function (callback) {
} }
if (checkboxes[7]) { if (checkboxes[7]) {
helper.interval.add('debug_pull', function debug_data_pull() { interval.add('debug_pull', function debug_data_pull() {
/* /*
* Enable balancer * Enable balancer
*/ */
if (helper.mspQueue.shouldDrop()) { if (mspQueue.shouldDrop()) {
update_debug_graphs(); update_debug_graphs();
return; return;
} }
@ -516,65 +534,65 @@ TABS.sensors.initialize = function (callback) {
if (checkboxes[0]) { if (checkboxes[0]) {
updateGraphHelperSize(gyroHelpers); updateGraphHelperSize(gyroHelpers);
samples_gyro_i = addSampleToData(gyro_data, samples_gyro_i, SENSOR_DATA.gyroscope); samples_gyro_i = addSampleToData(gyro_data, samples_gyro_i, FC.SENSOR_DATA.gyroscope);
drawGraph(gyroHelpers, gyro_data, samples_gyro_i); drawGraph(gyroHelpers, gyro_data, samples_gyro_i);
raw_data_text_ements.x[0].text(SENSOR_DATA.gyroscope[0].toFixed(2)); raw_data_text_ements.x[0].text(FC.SENSOR_DATA.gyroscope[0].toFixed(2));
raw_data_text_ements.y[0].text(SENSOR_DATA.gyroscope[1].toFixed(2)); raw_data_text_ements.y[0].text(FC.SENSOR_DATA.gyroscope[1].toFixed(2));
raw_data_text_ements.z[0].text(SENSOR_DATA.gyroscope[2].toFixed(2)); raw_data_text_ements.z[0].text(FC.SENSOR_DATA.gyroscope[2].toFixed(2));
} }
if (checkboxes[1]) { if (checkboxes[1]) {
updateGraphHelperSize(accelHelpers); updateGraphHelperSize(accelHelpers);
samples_accel_i = addSampleToData(accel_data, samples_accel_i, SENSOR_DATA.accelerometer); samples_accel_i = addSampleToData(accel_data, samples_accel_i, FC.SENSOR_DATA.accelerometer);
drawGraph(accelHelpers, accel_data, samples_accel_i); drawGraph(accelHelpers, accel_data, samples_accel_i);
raw_data_text_ements.x[1].text(SENSOR_DATA.accelerometer[0].toFixed(2)); raw_data_text_ements.x[1].text(FC.SENSOR_DATA.accelerometer[0].toFixed(2));
raw_data_text_ements.y[1].text(SENSOR_DATA.accelerometer[1].toFixed(2)); raw_data_text_ements.y[1].text(FC.SENSOR_DATA.accelerometer[1].toFixed(2));
raw_data_text_ements.z[1].text(SENSOR_DATA.accelerometer[2].toFixed(2)); raw_data_text_ements.z[1].text(FC.SENSOR_DATA.accelerometer[2].toFixed(2));
} }
if (checkboxes[2]) { if (checkboxes[2]) {
updateGraphHelperSize(magHelpers); updateGraphHelperSize(magHelpers);
samples_mag_i = addSampleToData(mag_data, samples_mag_i, SENSOR_DATA.magnetometer); samples_mag_i = addSampleToData(mag_data, samples_mag_i, FC.SENSOR_DATA.magnetometer);
drawGraph(magHelpers, mag_data, samples_mag_i); drawGraph(magHelpers, mag_data, samples_mag_i);
raw_data_text_ements.x[2].text(SENSOR_DATA.magnetometer[0].toFixed(2)); raw_data_text_ements.x[2].text(FC.SENSOR_DATA.magnetometer[0].toFixed(2));
raw_data_text_ements.y[2].text(SENSOR_DATA.magnetometer[1].toFixed(2)); raw_data_text_ements.y[2].text(FC.SENSOR_DATA.magnetometer[1].toFixed(2));
raw_data_text_ements.z[2].text(SENSOR_DATA.magnetometer[2].toFixed(2)); raw_data_text_ements.z[2].text(FC.SENSOR_DATA.magnetometer[2].toFixed(2));
} }
} }
function update_altitude_graph() { function update_altitude_graph() {
updateGraphHelperSize(altitudeHelpers); updateGraphHelperSize(altitudeHelpers);
samples_altitude_i = addSampleToData(altitude_data, samples_altitude_i, [SENSOR_DATA.altitude, SENSOR_DATA.barometer]); samples_altitude_i = addSampleToData(altitude_data, samples_altitude_i, [FC.SENSOR_DATA.altitude, FC.SENSOR_DATA.barometer]);
drawGraph(altitudeHelpers, altitude_data, samples_altitude_i); drawGraph(altitudeHelpers, altitude_data, samples_altitude_i);
raw_data_text_ements.x[3].text(SENSOR_DATA.altitude.toFixed(2)); raw_data_text_ements.x[3].text(FC.SENSOR_DATA.altitude.toFixed(2));
raw_data_text_ements.y[3].text(SENSOR_DATA.barometer.toFixed(2)); raw_data_text_ements.y[3].text(FC.SENSOR_DATA.barometer.toFixed(2));
} }
function update_sonar_graphs() { function update_sonar_graphs() {
updateGraphHelperSize(sonarHelpers); updateGraphHelperSize(sonarHelpers);
samples_sonar_i = addSampleToData(sonar_data, samples_sonar_i, [SENSOR_DATA.sonar]); samples_sonar_i = addSampleToData(sonar_data, samples_sonar_i, [FC.SENSOR_DATA.sonar]);
drawGraph(sonarHelpers, sonar_data, samples_sonar_i); drawGraph(sonarHelpers, sonar_data, samples_sonar_i);
raw_data_text_ements.x[4].text(SENSOR_DATA.sonar.toFixed(2)); raw_data_text_ements.x[4].text(FC.SENSOR_DATA.sonar.toFixed(2));
} }
function update_airspeed_graphs() { function update_airspeed_graphs() {
updateGraphHelperSize(airspeedHelpers); updateGraphHelperSize(airspeedHelpers);
samples_airspeed_i = addSampleToData(airspeed_data, samples_airspeed_i, [SENSOR_DATA.air_speed]); samples_airspeed_i = addSampleToData(airspeed_data, samples_airspeed_i, [FC.SENSOR_DATA.air_speed]);
drawGraph(airspeedHelpers, airspeed_data, samples_airspeed_i); drawGraph(airspeedHelpers, airspeed_data, samples_airspeed_i);
raw_data_text_ements.x[5].text(SENSOR_DATA.air_speed); raw_data_text_ements.x[5].text(FC.SENSOR_DATA.air_speed);
} }
function update_temperature_graphs() { function update_temperature_graphs() {
for (var i = 0; i < 8; i++) { for (var i = 0; i < 8; i++) {
updateGraphHelperSize(temperatureHelpers[i]); updateGraphHelperSize(temperatureHelpers[i]);
addSampleToData(temperature_data[i], samples_temperature_i, [SENSOR_DATA.temperature[i]]); addSampleToData(temperature_data[i], samples_temperature_i, [FC.SENSOR_DATA.temperature[i]]);
drawGraph(temperatureHelpers[i], temperature_data[i], samples_temperature_i); drawGraph(temperatureHelpers[i], temperature_data[i], samples_temperature_i);
raw_data_text_ements.x[6 + i].text(SENSOR_DATA.temperature[i]); raw_data_text_ements.x[6 + i].text(FC.SENSOR_DATA.temperature[i]);
} }
samples_temperature_i++; samples_temperature_i++;
} }
@ -583,34 +601,19 @@ TABS.sensors.initialize = function (callback) {
for (var i = 0; i < 8; i++) { for (var i = 0; i < 8; i++) {
updateGraphHelperSize(debugHelpers[i]); updateGraphHelperSize(debugHelpers[i]);
addSampleToData(debug_data[i], samples_debug_i, [SENSOR_DATA.debug[i]]); addSampleToData(debug_data[i], samples_debug_i, [FC.SENSOR_DATA.debug[i]]);
drawGraph(debugHelpers[i], debug_data[i], samples_debug_i); drawGraph(debugHelpers[i], debug_data[i], samples_debug_i);
raw_data_text_ements.x[6 + 8 + i].text(SENSOR_DATA.debug[i]); raw_data_text_ements.x[6 + 8 + i].text(FC.SENSOR_DATA.debug[i]);
} }
samples_debug_i++; samples_debug_i++;
} }
}); }
$("a.debug-trace").on('click', function () { $("a.debug-trace").on('click', function () {
var windowWidth = 500; var debugWin = window.open("tabs/debug_trace.html", "receiver_msp", "width=500,height=510,menubar=no,contextIsolation=no,nodeIntegration=yes");
var windowHeight = 510; debugWin.window.getDebugTrace = function () { return FC.DEBUG_TRACE || ''; };
window.open("/tabs/debug_trace.html", {
id: "debug_trace",
innerBounds: {
minWidth: windowWidth, minHeight: windowHeight,
width: windowWidth, height: windowHeight,
},
alwaysOnTop: true
}, function (createdWindow) {
createdWindow.contentWindow.getDebugTrace = function () { return DEBUG_TRACE || ''; };
return true;
});
return false;
}); });
GUI.content_ready(callback); GUI.content_ready(callback);
}); });
}; };

View file

@ -13,7 +13,6 @@ const mspBalancedInterval = require('./../js/msp_balanced_interval');
const interval = require('./../js/intervals'); const interval = require('./../js/intervals');
const mspQueue = require('./../js/serial_queue'); const mspQueue = require('./../js/serial_queue');
const SerialBackend = require('./../js/serial_backend'); const SerialBackend = require('./../js/serial_backend');
const { mixer } = require('./../js/model'); const { mixer } = require('./../js/model');
const BitHelper = require('./../js/bitHelper') const BitHelper = require('./../js/bitHelper')
@ -255,7 +254,7 @@ TABS.setup.initialize3D = function () {
if (useWebGlRenderer) { if (useWebGlRenderer) {
if (FC.MIXER_CONFIG.appliedMixerPreset === -1) { if (FC.MIXER_CONFIG.appliedMixerPreset === -1) {
model_file = 'custom'; model_file = 'custom';
GUI_control.prototype.log("<span style='color: red; font-weight: bolder'><strong>" + i18n.getMessage("mixerNotConfigured") + "</strong></span>"); GUI.log("<span style='color: red; font-weight: bolder'><strong>" + i18n.getMessage("mixerNotConfigured") + "</strong></span>");
} else { } else {
model_file = mixer.getById(FC.MIXER_CONFIG.appliedMixerPreset).model; model_file = mixer.getById(FC.MIXER_CONFIG.appliedMixerPreset).model;
} }