How to use this.setWifiState method in Appium Android Driver

Best JavaScript code snippet using appium-android-driver

location-678d6ac1.js

Source:location-678d6ac1.js Github

copy

Full Screen

1import { l as Plugins, r as registerPlugin, W as Webapi, a as storage } from './webapi-4204925e.js';2import { _ as __extends, c as cordova$1, e as Injectable, I as IonicNativePlugin, b as cordovaPropertyGet, d as cordovaPropertySet, m as msg, u as util } from './navigation-c2948117.js';3var LocationAccuracy = /** @class */ (function (_super) {4 __extends(LocationAccuracy, _super);5 function LocationAccuracy() {6 var _this = _super !== null && _super.apply(this, arguments) || this;7 /**8 * Convenience constant9 * @type {number}10 */11 _this.REQUEST_PRIORITY_NO_POWER = 0;12 /**13 * Convenience constant14 * @type {number}15 */16 _this.REQUEST_PRIORITY_LOW_POWER = 1;17 /**18 * Convenience constant19 * @type {number}20 */21 _this.REQUEST_PRIORITY_BALANCED_POWER_ACCURACY = 2;22 /**23 * Convenience constant24 * @type {number}25 */26 _this.REQUEST_PRIORITY_HIGH_ACCURACY = 3;27 /**28 * Convenience constant29 * @type {number}30 */31 _this.SUCCESS_SETTINGS_SATISFIED = 0;32 /**33 * Convenience constant34 * @type {number}35 */36 _this.SUCCESS_USER_AGREED = 1;37 /**38 * Convenience constant39 * @type {number}40 */41 _this.ERROR_ALREADY_REQUESTING = -1;42 /**43 * Convenience constant44 * @type {number}45 */46 _this.ERROR_INVALID_ACTION = 0;47 /**48 * Convenience constant49 * @type {number}50 */51 _this.ERROR_INVALID_ACCURACY = 1;52 /**53 * Convenience constant54 * @type {number}55 */56 _this.ERROR_EXCEPTION = 1;57 /**58 * Convenience constant59 * @type {number}60 */61 _this.ERROR_CANNOT_CHANGE_ACCURACY = 3;62 /**63 * Convenience constant64 * @type {number}65 */66 _this.ERROR_USER_DISAGREED = 4;67 /**68 * Convenience constant69 * @type {number}70 */71 _this.ERROR_GOOGLE_API_CONNECTION_FAILED = 4;72 return _this;73 }74 LocationAccuracy.prototype.canRequest = function () { return cordova$1(this, "canRequest", {}, arguments); };75 LocationAccuracy.prototype.isRequesting = function () { return cordova$1(this, "isRequesting", {}, arguments); };76 LocationAccuracy.prototype.request = function (accuracy) { return cordova$1(this, "request", { "callbackOrder": "reverse" }, arguments); };77 LocationAccuracy.pluginName = "LocationAccuracy";78 LocationAccuracy.plugin = "cordova-plugin-request-location-accuracy";79 LocationAccuracy.pluginRef = "cordova.plugins.locationAccuracy";80 LocationAccuracy.repo = "https://github.com/dpa99c/cordova-plugin-request-location-accuracy";81 LocationAccuracy.platforms = ["Android", "iOS"];82 LocationAccuracy.decorators = [83 { type: Injectable }84 ];85 return LocationAccuracy;86}(IonicNativePlugin));87var Diagnostic = /** @class */ (function (_super) {88 __extends(Diagnostic, _super);89 function Diagnostic() {90 var _this = _super !== null && _super.apply(this, arguments) || this;91 _this.permission = {92 READ_CALENDAR: 'READ_CALENDAR',93 WRITE_CALENDAR: 'WRITE_CALENDAR',94 CAMERA: 'CAMERA',95 READ_CONTACTS: 'READ_CONTACTS',96 WRITE_CONTACTS: 'WRITE_CONTACTS',97 GET_ACCOUNTS: 'GET_ACCOUNTS',98 ACCESS_FINE_LOCATION: 'ACCESS_FINE_LOCATION',99 ACCESS_COARSE_LOCATION: 'ACCESS_COARSE_LOCATION',100 RECORD_AUDIO: 'RECORD_AUDIO',101 READ_PHONE_STATE: 'READ_PHONE_STATE',102 CALL_PHONE: 'CALL_PHONE',103 ADD_VOICEMAIL: 'ADD_VOICEMAIL',104 USE_SIP: 'USE_SIP',105 PROCESS_OUTGOING_CALLS: 'PROCESS_OUTGOING_CALLS',106 READ_CALL_LOG: 'READ_CALL_LOG',107 WRITE_CALL_LOG: 'WRITE_CALL_LOG',108 SEND_SMS: 'SEND_SMS',109 RECEIVE_SMS: 'RECEIVE_SMS',110 READ_SMS: 'READ_SMS',111 RECEIVE_WAP_PUSH: 'RECEIVE_WAP_PUSH',112 RECEIVE_MMS: 'RECEIVE_MMS',113 WRITE_EXTERNAL_STORAGE: 'WRITE_EXTERNAL_STORAGE',114 READ_EXTERNAL_STORAGE: 'READ_EXTERNAL_STORAGE',115 BODY_SENSORS: 'BODY_SENSORS',116 };117 _this.locationAuthorizationMode = {118 ALWAYS: 'always',119 WHEN_IN_USE: 'when_in_use',120 };121 _this.permissionGroups = {122 CALENDAR: ['READ_CALENDAR', 'WRITE_CALENDAR'],123 CAMERA: ['CAMERA'],124 CONTACTS: ['READ_CONTACTS', 'WRITE_CONTACTS', 'GET_ACCOUNTS'],125 LOCATION: ['ACCESS_FINE_LOCATION', 'ACCESS_COARSE_LOCATION'],126 MICROPHONE: ['RECORD_AUDIO'],127 PHONE: [128 'READ_PHONE_STATE',129 'CALL_PHONE',130 'ADD_VOICEMAIL',131 'USE_SIP',132 'PROCESS_OUTGOING_CALLS',133 'READ_CALL_LOG',134 'WRITE_CALL_LOG',135 ],136 SENSORS: ['BODY_SENSORS'],137 SMS: ['SEND_SMS', 'RECEIVE_SMS', 'READ_SMS', 'RECEIVE_WAP_PUSH', 'RECEIVE_MMS'],138 STORAGE: ['READ_EXTERNAL_STORAGE', 'WRITE_EXTERNAL_STORAGE'],139 };140 _this.locationMode = {141 HIGH_ACCURACY: 'high_accuracy',142 DEVICE_ONLY: 'device_only',143 BATTERY_SAVING: 'battery_saving',144 LOCATION_OFF: 'location_off',145 };146 _this.bluetoothState = {147 UNKNOWN: 'unknown',148 RESETTING: 'resetting',149 UNSUPPORTED: 'unsupported',150 UNAUTHORIZED: 'unauthorized',151 POWERED_OFF: 'powered_off',152 POWERED_ON: 'powered_on',153 POWERING_OFF: 'powering_off',154 POWERING_ON: 'powering_on',155 };156 return _this;157 }158 Diagnostic.prototype.isLocationAvailable = function () { return cordova$1(this, "isLocationAvailable", {}, arguments); };159 Diagnostic.prototype.isWifiAvailable = function () { return cordova$1(this, "isWifiAvailable", {}, arguments); };160 Diagnostic.prototype.isCameraAvailable = function (externalStorage) { return cordova$1(this, "isCameraAvailable", { "callbackOrder": "reverse" }, arguments); };161 Diagnostic.prototype.isBluetoothAvailable = function () { return cordova$1(this, "isBluetoothAvailable", {}, arguments); };162 Diagnostic.prototype.switchToLocationSettings = function () { return cordova$1(this, "switchToLocationSettings", { "sync": true, "platforms": ["Android", "Windows 10", "iOS"] }, arguments); };163 Diagnostic.prototype.switchToMobileDataSettings = function () { return cordova$1(this, "switchToMobileDataSettings", { "sync": true, "platforms": ["Android", "Windows 10"] }, arguments); };164 Diagnostic.prototype.switchToBluetoothSettings = function () { return cordova$1(this, "switchToBluetoothSettings", { "sync": true, "platforms": ["Android", "Windows 10"] }, arguments); };165 Diagnostic.prototype.switchToWifiSettings = function () { return cordova$1(this, "switchToWifiSettings", { "sync": true, "platforms": ["Android", "Windows 10"] }, arguments); };166 Diagnostic.prototype.isWifiEnabled = function () { return cordova$1(this, "isWifiEnabled", { "platforms": ["Android", "Windows 10"] }, arguments); };167 Diagnostic.prototype.setWifiState = function (state) { return cordova$1(this, "setWifiState", { "callbackOrder": "reverse", "platforms": ["Android", "Windows 10"] }, arguments); };168 Diagnostic.prototype.setBluetoothState = function (state) { return cordova$1(this, "setBluetoothState", { "callbackOrder": "reverse", "platforms": ["Android", "Windows 10"] }, arguments); };169 Diagnostic.prototype.isLocationEnabled = function () { return cordova$1(this, "isLocationEnabled", { "platforms": ["Android", "iOS"] }, arguments); };170 Diagnostic.prototype.isLocationAuthorized = function () { return cordova$1(this, "isLocationAuthorized", {}, arguments); };171 Diagnostic.prototype.getLocationAuthorizationStatus = function () { return cordova$1(this, "getLocationAuthorizationStatus", { "platforms": ["Android", "iOS"] }, arguments); };172 Diagnostic.prototype.requestLocationAuthorization = function (mode) { return cordova$1(this, "requestLocationAuthorization", { "platforms": ["Android", "iOS"], "callbackOrder": "reverse" }, arguments); };173 Diagnostic.prototype.isCameraPresent = function () { return cordova$1(this, "isCameraPresent", { "platforms": ["Android", "iOS"] }, arguments); };174 Diagnostic.prototype.isCameraAuthorized = function (externalStorage) { return cordova$1(this, "isCameraAuthorized", { "platforms": ["Android", "iOS"], "callbackOrder": "reverse" }, arguments); };175 Diagnostic.prototype.getCameraAuthorizationStatus = function (externalStorage) { return cordova$1(this, "getCameraAuthorizationStatus", { "platforms": ["Android", "iOS"], "callbackOrder": "reverse" }, arguments); };176 Diagnostic.prototype.requestCameraAuthorization = function (externalStorage) { return cordova$1(this, "requestCameraAuthorization", { "platforms": ["Android", "iOS"], "callbackOrder": "reverse" }, arguments); };177 Diagnostic.prototype.isMicrophoneAuthorized = function () { return cordova$1(this, "isMicrophoneAuthorized", { "platforms": ["Android", "iOS"] }, arguments); };178 Diagnostic.prototype.getMicrophoneAuthorizationStatus = function () { return cordova$1(this, "getMicrophoneAuthorizationStatus", { "platforms": ["Android", "iOS"] }, arguments); };179 Diagnostic.prototype.requestMicrophoneAuthorization = function () { return cordova$1(this, "requestMicrophoneAuthorization", { "platforms": ["Android", "iOS"] }, arguments); };180 Diagnostic.prototype.isContactsAuthorized = function () { return cordova$1(this, "isContactsAuthorized", { "platforms": ["Android", "iOS"] }, arguments); };181 Diagnostic.prototype.getContactsAuthorizationStatus = function () { return cordova$1(this, "getContactsAuthorizationStatus", { "platforms": ["Android", "iOS"] }, arguments); };182 Diagnostic.prototype.requestContactsAuthorization = function () { return cordova$1(this, "requestContactsAuthorization", { "platforms": ["Android", "iOS"] }, arguments); };183 Diagnostic.prototype.isCalendarAuthorized = function () { return cordova$1(this, "isCalendarAuthorized", { "platforms": ["Android", "iOS"] }, arguments); };184 Diagnostic.prototype.getCalendarAuthorizationStatus = function () { return cordova$1(this, "getCalendarAuthorizationStatus", { "platforms": ["Android", "iOS"] }, arguments); };185 Diagnostic.prototype.requestCalendarAuthorization = function () { return cordova$1(this, "requestCalendarAuthorization", { "platforms": ["Android", "iOS"] }, arguments); };186 Diagnostic.prototype.switchToSettings = function () { return cordova$1(this, "switchToSettings", { "platforms": ["Android", "iOS"] }, arguments); };187 Diagnostic.prototype.getBluetoothState = function () { return cordova$1(this, "getBluetoothState", { "platforms": ["Android", "iOS"] }, arguments); };188 Diagnostic.prototype.registerBluetoothStateChangeHandler = function (handler) { return cordova$1(this, "registerBluetoothStateChangeHandler", { "platforms": ["Android", "iOS"], "sync": true }, arguments); };189 Diagnostic.prototype.registerLocationStateChangeHandler = function (handler) { return cordova$1(this, "registerLocationStateChangeHandler", { "platforms": ["Android", "iOS"], "sync": true }, arguments); };190 Diagnostic.prototype.isGpsLocationAvailable = function () { return cordova$1(this, "isGpsLocationAvailable", { "platforms": ["Android"] }, arguments); };191 Diagnostic.prototype.isGpsLocationEnabled = function () { return cordova$1(this, "isGpsLocationEnabled", { "platforms": ["Android"] }, arguments); };192 Diagnostic.prototype.isNetworkLocationAvailable = function () { return cordova$1(this, "isNetworkLocationAvailable", { "platforms": ["Android"] }, arguments); };193 Diagnostic.prototype.isNetworkLocationEnabled = function () { return cordova$1(this, "isNetworkLocationEnabled", { "platforms": ["Android"] }, arguments); };194 Diagnostic.prototype.getLocationMode = function () { return cordova$1(this, "getLocationMode", { "platforms": ["Android"] }, arguments); };195 Diagnostic.prototype.getPermissionAuthorizationStatus = function (permission) { return cordova$1(this, "getPermissionAuthorizationStatus", { "platforms": ["Android"], "callbackOrder": "reverse" }, arguments); };196 Diagnostic.prototype.getPermissionsAuthorizationStatus = function (permissions) { return cordova$1(this, "getPermissionsAuthorizationStatus", { "platforms": ["Android"], "callbackOrder": "reverse" }, arguments); };197 Diagnostic.prototype.requestRuntimePermission = function (permission) { return cordova$1(this, "requestRuntimePermission", { "platforms": ["Android"], "callbackOrder": "reverse" }, arguments); };198 Diagnostic.prototype.requestRuntimePermissions = function (permissions) { return cordova$1(this, "requestRuntimePermissions", { "platforms": ["Android"], "callbackOrder": "reverse" }, arguments); };199 Diagnostic.prototype.isRequestingPermission = function () { return cordova$1(this, "isRequestingPermission", { "sync": true }, arguments); };200 Diagnostic.prototype.registerPermissionRequestCompleteHandler = function (handler) { return cordova$1(this, "registerPermissionRequestCompleteHandler", { "sync": true }, arguments); };201 Diagnostic.prototype.isBluetoothEnabled = function () { return cordova$1(this, "isBluetoothEnabled", { "platforms": ["Android"] }, arguments); };202 Diagnostic.prototype.hasBluetoothSupport = function () { return cordova$1(this, "hasBluetoothSupport", { "platforms": ["Android"] }, arguments); };203 Diagnostic.prototype.hasBluetoothLESupport = function () { return cordova$1(this, "hasBluetoothLESupport", { "platforms": ["Android"] }, arguments); };204 Diagnostic.prototype.hasBluetoothLEPeripheralSupport = function () { return cordova$1(this, "hasBluetoothLEPeripheralSupport", { "platforms": ["Android"] }, arguments); };205 Diagnostic.prototype.isExternalStorageAuthorized = function () { return cordova$1(this, "isExternalStorageAuthorized", { "platforms": ["Android"] }, arguments); };206 Diagnostic.prototype.getExternalStorageAuthorizationStatus = function () { return cordova$1(this, "getExternalStorageAuthorizationStatus", { "platforms": ["Android"] }, arguments); };207 Diagnostic.prototype.requestExternalStorageAuthorization = function () { return cordova$1(this, "requestExternalStorageAuthorization", { "platforms": ["Android"] }, arguments); };208 Diagnostic.prototype.getExternalSdCardDetails = function () { return cordova$1(this, "getExternalSdCardDetails", { "platforms": ["Android"] }, arguments); };209 Diagnostic.prototype.switchToWirelessSettings = function () { return cordova$1(this, "switchToWirelessSettings", { "platforms": ["Android"], "sync": true }, arguments); };210 Diagnostic.prototype.switchToNFCSettings = function () { return cordova$1(this, "switchToNFCSettings", { "platforms": ["Android"], "sync": true }, arguments); };211 Diagnostic.prototype.isNFCPresent = function () { return cordova$1(this, "isNFCPresent", { "platforms": ["Android"] }, arguments); };212 Diagnostic.prototype.isNFCEnabled = function () { return cordova$1(this, "isNFCEnabled", { "platforms": ["Android"] }, arguments); };213 Diagnostic.prototype.isNFCAvailable = function () { return cordova$1(this, "isNFCAvailable", { "platforms": ["Android"] }, arguments); };214 Diagnostic.prototype.registerNFCStateChangeHandler = function (handler) { return cordova$1(this, "registerNFCStateChangeHandler", { "platforms": ["Android"], "sync": true }, arguments); };215 Diagnostic.prototype.isDataRoamingEnabled = function () { return cordova$1(this, "isDataRoamingEnabled", { "platforms": ["Android"] }, arguments); };216 Diagnostic.prototype.isADBModeEnabled = function () { return cordova$1(this, "isADBModeEnabled", { "platforms": ["Android"] }, arguments); };217 Diagnostic.prototype.isDeviceRooted = function () { return cordova$1(this, "isDeviceRooted", { "platforms": ["Android"] }, arguments); };218 Diagnostic.prototype.isCameraRollAuthorized = function () { return cordova$1(this, "isCameraRollAuthorized", { "platforms": ["iOS"] }, arguments); };219 Diagnostic.prototype.getCameraRollAuthorizationStatus = function () { return cordova$1(this, "getCameraRollAuthorizationStatus", { "platforms": ["iOS"] }, arguments); };220 Diagnostic.prototype.requestCameraRollAuthorization = function () { return cordova$1(this, "requestCameraRollAuthorization", { "platforms": ["iOS"] }, arguments); };221 Diagnostic.prototype.isRemoteNotificationsEnabled = function () { return cordova$1(this, "isRemoteNotificationsEnabled", { "platforms": ["iOS", "Android"] }, arguments); };222 Diagnostic.prototype.isRegisteredForRemoteNotifications = function () { return cordova$1(this, "isRegisteredForRemoteNotifications", { "platforms": ["iOS"] }, arguments); };223 Diagnostic.prototype.getRemoteNotificationsAuthorizationStatus = function () { return cordova$1(this, "getRemoteNotificationsAuthorizationStatus", { "platforms": ["iOS"] }, arguments); };224 Diagnostic.prototype.requestRemoteNotificationsAuthorization = function (types, omitRegistration) { return cordova$1(this, "requestRemoteNotificationsAuthorization", { "platforms": ["iOS"] }, arguments); };225 Diagnostic.prototype.getRemoteNotificationTypes = function () { return cordova$1(this, "getRemoteNotificationTypes", { "platforms": ["iOS"] }, arguments); };226 Diagnostic.prototype.isRemindersAuthorized = function () { return cordova$1(this, "isRemindersAuthorized", { "platforms": ["iOS"] }, arguments); };227 Diagnostic.prototype.getRemindersAuthorizationStatus = function () { return cordova$1(this, "getRemindersAuthorizationStatus", { "platforms": ["iOS"] }, arguments); };228 Diagnostic.prototype.requestRemindersAuthorization = function () { return cordova$1(this, "requestRemindersAuthorization", { "platforms": ["iOS"] }, arguments); };229 Diagnostic.prototype.isBackgroundRefreshAuthorized = function () { return cordova$1(this, "isBackgroundRefreshAuthorized", { "platforms": ["iOS"] }, arguments); };230 Diagnostic.prototype.getBackgroundRefreshStatus = function () { return cordova$1(this, "getBackgroundRefreshStatus", { "platforms": ["iOS"] }, arguments); };231 Diagnostic.prototype.requestBluetoothAuthorization = function () { return cordova$1(this, "requestBluetoothAuthorization", { "platforms": ["iOS"] }, arguments); };232 Diagnostic.prototype.isMotionAvailable = function () { return cordova$1(this, "isMotionAvailable", { "platforms": ["iOS"] }, arguments); };233 Diagnostic.prototype.isMotionRequestOutcomeAvailable = function () { return cordova$1(this, "isMotionRequestOutcomeAvailable", { "platforms": ["iOS"] }, arguments); };234 Diagnostic.prototype.requestMotionAuthorization = function () { return cordova$1(this, "requestMotionAuthorization", { "platforms": ["iOS"] }, arguments); };235 Diagnostic.prototype.getMotionAuthorizationStatus = function () { return cordova$1(this, "getMotionAuthorizationStatus", { "platforms": ["iOS"] }, arguments); };236 Diagnostic.prototype.getLocationAccuracyAuthorization = function () { return cordova$1(this, "getLocationAccuracyAuthorization", { "platform": ["iOS"] }, arguments); };237 Diagnostic.prototype.requestTemporaryFullAccuracyAuthorization = function (purpose) { return cordova$1(this, "requestTemporaryFullAccuracyAuthorization", { "platforms": ["iOS"] }, arguments); };238 Diagnostic.prototype.registerLocationAccuracyAuthorizationChangeHandler = function (handler) { return cordova$1(this, "registerLocationAccuracyAuthorizationChangeHandler", { "platforms": ["iOS"], "sync": true }, arguments); };239 Object.defineProperty(Diagnostic.prototype, "permissionStatus", {240 get: function () { return cordovaPropertyGet(this, "permissionStatus"); },241 set: function (value) { cordovaPropertySet(this, "permissionStatus", value); },242 enumerable: false,243 configurable: true244 });245 Object.defineProperty(Diagnostic.prototype, "NFCState", {246 get: function () { return cordovaPropertyGet(this, "NFCState"); },247 set: function (value) { cordovaPropertySet(this, "NFCState", value); },248 enumerable: false,249 configurable: true250 });251 Object.defineProperty(Diagnostic.prototype, "motionStatus", {252 get: function () { return cordovaPropertyGet(this, "motionStatus"); },253 set: function (value) { cordovaPropertySet(this, "motionStatus", value); },254 enumerable: false,255 configurable: true256 });257 Diagnostic.pluginName = "Diagnostic";258 Diagnostic.plugin = "cordova.plugins.diagnostic";259 Diagnostic.pluginRef = "cordova.plugins.diagnostic";260 Diagnostic.repo = "https://github.com/dpa99c/cordova-diagnostic-plugin";261 Diagnostic.platforms = ["Android", "iOS", "Windows"];262 Diagnostic.decorators = [263 { type: Injectable }264 ];265 return Diagnostic;266}(IonicNativePlugin));267var OpenNativeSettings = /** @class */ (function (_super) {268 __extends(OpenNativeSettings, _super);269 function OpenNativeSettings() {270 return _super !== null && _super.apply(this, arguments) || this;271 }272 OpenNativeSettings.prototype.open = function (setting) { return cordova$1(this, "open", {}, arguments); };273 OpenNativeSettings.pluginName = "OpenNativeSettings";274 OpenNativeSettings.plugin = "cordova-open-native-settings";275 OpenNativeSettings.pluginRef = "cordova.plugins.settings";276 OpenNativeSettings.repo = "https://github.com/guyromb/Cordova-open-native-settings";277 OpenNativeSettings.platforms = ["Android", "iOS"];278 OpenNativeSettings.decorators = [279 { type: Injectable }280 ];281 return OpenNativeSettings;282}(IonicNativePlugin));283var NativeModule = Plugins.BackgroundGeolocation;284var LOG_LEVEL_DEBUG = "debug";285var LOG_LEVEL_NOTICE = "notice";286var LOG_LEVEL_INFO = "info";287var LOG_LEVEL_WARN = "warn";288var LOG_LEVEL_ERROR = "error";289var ORDER_ASC = 1;290var ORDER_DESC = -1;291function log(level, msg) {292 return NativeModule.log({293 level: level,294 message: msg295 });296}297function validateQuery(query) {298 if (typeof (query) !== 'object')299 return {};300 if (query.hasOwnProperty('start') && isNaN(query.start)) {301 throw new Error('Invalid SQLQuery.start. Expected unix timestamp but received: ' + query.start);302 }303 if (query.hasOwnProperty('end') && isNaN(query.end)) {304 throw new Error('Invalid SQLQuery.end. Expected unix timestamp but received: ' + query.end);305 }306 return query;307}308var Logger = /** @class */ (function () {309 function Logger() {310 }311 Object.defineProperty(Logger, "ORDER_ASC", {312 get: function () { return ORDER_ASC; },313 enumerable: false,314 configurable: true315 });316 Object.defineProperty(Logger, "ORDER_DESC", {317 get: function () { return ORDER_DESC; },318 enumerable: false,319 configurable: true320 });321 Logger.debug = function (msg) {322 return log(LOG_LEVEL_DEBUG, msg);323 };324 Logger.error = function (msg) {325 return log(LOG_LEVEL_ERROR, msg);326 };327 Logger.warn = function (msg) {328 return log(LOG_LEVEL_WARN, msg);329 };330 Logger.info = function (msg) {331 return log(LOG_LEVEL_INFO, msg);332 };333 Logger.notice = function (msg) {334 return log(LOG_LEVEL_NOTICE, msg);335 };336 Logger.getLog = function (query) {337 query = validateQuery(query);338 return new Promise(function (resolve, reject) {339 NativeModule.getLog({ options: query }).then(function (result) {340 resolve(result.log);341 }).catch(function (error) {342 reject(error.message);343 });344 });345 };346 Logger.destroyLog = function () {347 return new Promise(function (resolve, reject) {348 NativeModule.destroyLog().then(function () {349 resolve();350 }).catch(function (error) {351 reject(error.message);352 });353 });354 };355 Logger.emailLog = function (email, query) {356 query = validateQuery(query);357 return new Promise(function (resolve, reject) {358 NativeModule.emailLog({ email: email, query: query }).then(function (result) {359 resolve(result);360 }).catch(function (error) {361 reject(error.message);362 });363 });364 };365 Logger.uploadLog = function (url, query) {366 query = validateQuery(query);367 return new Promise(function (resolve, reject) {368 NativeModule.emailLog({ url: url, query: query }).then(function () {369 resolve();370 }).catch(function (error) {371 reject(error.message);372 });373 });374 };375 return Logger;376}());377var NativeModule$1 = Plugins.BackgroundGeolocation;378var DEFAULT_URL = 'http://tracker.transistorsoft.com';379var DUMMY_TOKEN = 'DUMMY_TOKEN';380var REFRESH_PAYLOAD = {381 refresh_token: '{refreshToken}'382};383var LOCATIONS_PATH = '/api/locations';384var REFRESH_TOKEN_PATH = '/api/refresh_token';385var TransistorAuthorizationToken = /** @class */ (function () {386 function TransistorAuthorizationToken() {387 }388 TransistorAuthorizationToken.findOrCreate = function (orgname, username, url) {389 if (url === void 0) { url = DEFAULT_URL; }390 return new Promise(function (resolve, reject) {391 NativeModule$1.getTransistorToken({392 org: orgname,393 username: username,394 url: url395 }).then(function (result) {396 if (result.success) {397 var token = result.token;398 token.url = url;399 resolve(token);400 }401 else {402 console.warn('[TransistorAuthorizationToken findOrCreate] ERROR: ', result);403 if (result.status == '403') {404 reject(result);405 return;406 }407 resolve({408 accessToken: DUMMY_TOKEN,409 refreshToken: DUMMY_TOKEN,410 expires: -1,411 url: url412 });413 }414 }).catch(function (error) {415 reject(error);416 });417 });418 };419 TransistorAuthorizationToken.destroy = function (url) {420 if (url === void 0) { url = DEFAULT_URL; }421 return new Promise(function (resolve, reject) {422 NativeModule$1.destroyTransistorToken({ url: url }).then(function () {423 resolve();424 }).catch(function (error) {425 reject(error.message);426 });427 });428 };429 TransistorAuthorizationToken.applyIf = function (config) {430 if (!config.transistorAuthorizationToken)431 return config;432 var token = config.transistorAuthorizationToken;433 delete config.transistorAuthorizationToken;434 config.url = token.url + LOCATIONS_PATH;435 config.authorization = {436 strategy: 'JWT',437 accessToken: token.accessToken,438 refreshToken: token.refreshToken,439 refreshUrl: token.url + REFRESH_TOKEN_PATH,440 refreshPayload: REFRESH_PAYLOAD,441 expires: token.expires442 };443 return config;444 };445 return TransistorAuthorizationToken;446}());447var NativeModule$2 = Plugins.BackgroundGeolocation;448var IGNORE_BATTERY_OPTIMIZATIONS = "IGNORE_BATTERY_OPTIMIZATIONS";449var POWER_MANAGER = "POWER_MANAGER";450var resolveSettingsRequest = function (resolve, request) {451 if (request.lastSeenAt > 0) {452 request.lastSeenAt = new Date(request.lastSeenAt);453 }454 resolve(request);455};456var DeviceSettings = /** @class */ (function () {457 function DeviceSettings() {458 }459 DeviceSettings.isIgnoringBatteryOptimizations = function () {460 return new Promise(function (resolve, reject) {461 NativeModule$2.isIgnoringBatteryOptimizations.then(function (result) {462 resolve(result.isIgnoringBatteryOptimizations);463 }).catch(function (error) {464 reject(error.message);465 });466 });467 };468 DeviceSettings.showIgnoreBatteryOptimizations = function () {469 return new Promise(function (resolve, reject) {470 var args = { action: IGNORE_BATTERY_OPTIMIZATIONS };471 NativeModule$2.requestSettings(args).then(function (result) {472 resolveSettingsRequest(resolve, result);473 }).catch(function (error) {474 reject(error.message);475 });476 });477 };478 DeviceSettings.showPowerManager = function () {479 return new Promise(function (resolve, reject) {480 var args = { action: POWER_MANAGER };481 NativeModule$2.requestSettings(args).then(function (result) {482 resolveSettingsRequest(resolve, result);483 }).catch(function (error) {484 reject(error.message);485 });486 });487 };488 DeviceSettings.show = function (request) {489 return new Promise(function (resolve, reject) {490 var args = { action: request.action };491 NativeModule$2.showSettings(args).then(function () {492 resolve();493 }).catch(function (error) {494 reject(error.message);495 });496 });497 };498 return DeviceSettings;499}());500var Events = {501 BOOT: "boot",502 TERMINATE: "terminate",503 LOCATION: "location",504 HTTP: "http",505 MOTIONCHANGE: "motionchange",506 PROVIDERCHANGE: "providerchange",507 HEARTBEAT: "heartbeat",508 ACTIVITYCHANGE: "activitychange",509 GEOFENCE: "geofence",510 GEOFENCESCHANGE: "geofenceschange",511 SCHEDULE: "schedule",512 CONNECTIVITYCHANGE: "connectivitychange",513 ENABLEDCHANGE: "enabledchange",514 POWERSAVECHANGE: "powersavechange",515 NOTIFICATIONACTION: "notificationaction",516 AUTHORIZATION: "authorization",517};518var __awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {519 function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }520 return new (P || (P = Promise))(function (resolve, reject) {521 function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }522 function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }523 function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }524 step((generator = generator.apply(thisArg, _arguments || [])).next());525 });526};527var __generator = (undefined && undefined.__generator) || function (thisArg, body) {528 var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;529 return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;530 function verb(n) { return function (v) { return step([n, v]); }; }531 function step(op) {532 if (f) throw new TypeError("Generator is already executing.");533 while (_) try {534 if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;535 if (y = 0, t) op = [op[0] & 2, t.value];536 switch (op[0]) {537 case 0: case 1: t = op; break;538 case 4: _.label++; return { value: op[1], done: false };539 case 5: _.label++; y = op[1]; op = [0]; continue;540 case 7: op = _.ops.pop(); _.trys.pop(); continue;541 default:542 if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }543 if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }544 if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }545 if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }546 if (t[2]) _.ops.pop();547 _.trys.pop(); continue;548 }549 op = body.call(thisArg, _);550 } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }551 if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };552 }553};554var NativeModule$3 = registerPlugin('BackgroundGeolocation');555var TAG = "TSLocationManager";556/// Container for event-subscriptions.557var EVENT_SUBSCRIPTIONS = [];558/// Container for watchPostion subscriptions.559var WATCH_POSITION_SUBSCRIPTIONS = [];560/// Event handler Subscription561///562var Subscription = /** @class */ (function () {563 function Subscription(event, subscription, callback) {564 this.event = event;565 this.subscription = subscription;566 this.callback = callback;567 }568 return Subscription;569}());570/// Validate provided config for #ready, #setConfig, #reset.571var validateConfig = function (config) {572 // Detect obsolete notification* fields and re-map to Notification instance.573 if ((config.notificationPriority) ||574 (config.notificationText) ||575 (config.notificationTitle) ||576 (config.notificationChannelName) ||577 (config.notificationColor) ||578 (config.notificationSmallIcon) ||579 (config.notificationLargeIcon)) {580 console.warn('[BackgroundGeolocation] WARNING: Config.notification* fields (eg: notificationText) are all deprecated in favor of notification: {title: "My Title", text: "My Text"} See docs for "Notification" class');581 config.notification = {582 text: config.notificationText,583 title: config.notificationTitle,584 color: config.notificationColor,585 channelName: config.notificationChannelName,586 smallIcon: config.notificationSmallIcon,587 largeIcon: config.notificationLargeIcon,588 priority: config.notificationPriority589 };590 }591 config = TransistorAuthorizationToken.applyIf(config);592 return config;593};594var LOG_LEVEL_OFF = 0;595var LOG_LEVEL_ERROR$1 = 1;596var LOG_LEVEL_WARNING = 2;597var LOG_LEVEL_INFO$1 = 3;598var LOG_LEVEL_DEBUG$1 = 4;599var LOG_LEVEL_VERBOSE = 5;600var DESIRED_ACCURACY_NAVIGATION = -2;601var DESIRED_ACCURACY_HIGH = -1;602var DESIRED_ACCURACY_MEDIUM = 10;603var DESIRED_ACCURACY_LOW = 100;604var DESIRED_ACCURACY_VERY_LOW = 1000;605var DESIRED_ACCURACY_LOWEST = 3000;606var AUTHORIZATION_STATUS_NOT_DETERMINED = 0;607var AUTHORIZATION_STATUS_RESTRICTED = 1;608var AUTHORIZATION_STATUS_DENIED = 2;609var AUTHORIZATION_STATUS_ALWAYS = 3;610var AUTHORIZATION_STATUS_WHEN_IN_USE = 4;611var NOTIFICATION_PRIORITY_DEFAULT = 0;612var NOTIFICATION_PRIORITY_HIGH = 1;613var NOTIFICATION_PRIORITY_LOW = -1;614var NOTIFICATION_PRIORITY_MAX = 2;615var NOTIFICATION_PRIORITY_MIN = -2;616var ACTIVITY_TYPE_OTHER = 1;617var ACTIVITY_TYPE_AUTOMOTIVE_NAVIGATION = 2;618var ACTIVITY_TYPE_FITNESS = 3;619var ACTIVITY_TYPE_OTHER_NAVIGATION = 4;620var LOCATION_AUTHORIZATION_ALWAYS = "Always";621var LOCATION_AUTHORIZATION_WHEN_IN_USE = "WhenInUse";622var LOCATION_AUTHORIZATION_ANY = "Any";623var PERSIST_MODE_ALL = 2;624var PERSIST_MODE_LOCATION = 1;625var PERSIST_MODE_GEOFENCE = -1;626var PERSIST_MODE_NONE = 0;627var ACCURACY_AUTHORIZATION_FULL = 0;628var ACCURACY_AUTHORIZATION_REDUCED = 1;629/// BackgroundGeolocation JS API630var BackgroundGeolocation = /** @class */ (function () {631 function BackgroundGeolocation() {632 }633 Object.defineProperty(BackgroundGeolocation, "EVENT_BOOT", {634 /// Events635 get: function () { return Events.BOOT; },636 enumerable: false,637 configurable: true638 });639 Object.defineProperty(BackgroundGeolocation, "EVENT_TERMINATE", {640 get: function () { return Events.TERMINATE; },641 enumerable: false,642 configurable: true643 });644 Object.defineProperty(BackgroundGeolocation, "EVENT_LOCATION", {645 get: function () { return Events.LOCATION; },646 enumerable: false,647 configurable: true648 });649 Object.defineProperty(BackgroundGeolocation, "EVENT_MOTIONCHANGE", {650 get: function () { return Events.MOTIONCHANGE; },651 enumerable: false,652 configurable: true653 });654 Object.defineProperty(BackgroundGeolocation, "EVENT_HTTP", {655 get: function () { return Events.HTTP; },656 enumerable: false,657 configurable: true658 });659 Object.defineProperty(BackgroundGeolocation, "EVENT_HEARTBEAT", {660 get: function () { return Events.HEARTBEAT; },661 enumerable: false,662 configurable: true663 });664 Object.defineProperty(BackgroundGeolocation, "EVENT_PROVIDERCHANGE", {665 get: function () { return Events.PROVIDERCHANGE; },666 enumerable: false,667 configurable: true668 });669 Object.defineProperty(BackgroundGeolocation, "EVENT_ACTIVITYCHANGE", {670 get: function () { return Events.ACTIVITYCHANGE; },671 enumerable: false,672 configurable: true673 });674 Object.defineProperty(BackgroundGeolocation, "EVENT_GEOFENCE", {675 get: function () { return Events.GEOFENCE; },676 enumerable: false,677 configurable: true678 });679 Object.defineProperty(BackgroundGeolocation, "EVENT_GEOFENCESCHANGE", {680 get: function () { return Events.GEOFENCESCHANGE; },681 enumerable: false,682 configurable: true683 });684 Object.defineProperty(BackgroundGeolocation, "EVENT_ENABLEDCHANGE", {685 get: function () { return Events.ENABLEDCHANGE; },686 enumerable: false,687 configurable: true688 });689 Object.defineProperty(BackgroundGeolocation, "EVENT_CONNECTIVITYCHANGE", {690 get: function () { return Events.CONNECTIVITYCHANGE; },691 enumerable: false,692 configurable: true693 });694 Object.defineProperty(BackgroundGeolocation, "EVENT_SCHEDULE", {695 get: function () { return Events.SCHEDULE; },696 enumerable: false,697 configurable: true698 });699 Object.defineProperty(BackgroundGeolocation, "EVENT_POWERSAVECHANGE", {700 get: function () { return Events.POWERSAVECHANGE; },701 enumerable: false,702 configurable: true703 });704 Object.defineProperty(BackgroundGeolocation, "EVENT_NOTIFICATIONACTION", {705 get: function () { return Events.NOTIFICATIONACTION; },706 enumerable: false,707 configurable: true708 });709 Object.defineProperty(BackgroundGeolocation, "EVENT_AUTHORIZATION", {710 get: function () { return Events.AUTHORIZATION; },711 enumerable: false,712 configurable: true713 });714 Object.defineProperty(BackgroundGeolocation, "LOG_LEVEL_OFF", {715 get: function () { return LOG_LEVEL_OFF; },716 enumerable: false,717 configurable: true718 });719 Object.defineProperty(BackgroundGeolocation, "LOG_LEVEL_ERROR", {720 get: function () { return LOG_LEVEL_ERROR$1; },721 enumerable: false,722 configurable: true723 });724 Object.defineProperty(BackgroundGeolocation, "LOG_LEVEL_WARNING", {725 get: function () { return LOG_LEVEL_WARNING; },726 enumerable: false,727 configurable: true728 });729 Object.defineProperty(BackgroundGeolocation, "LOG_LEVEL_INFO", {730 get: function () { return LOG_LEVEL_INFO$1; },731 enumerable: false,732 configurable: true733 });734 Object.defineProperty(BackgroundGeolocation, "LOG_LEVEL_DEBUG", {735 get: function () { return LOG_LEVEL_DEBUG$1; },736 enumerable: false,737 configurable: true738 });739 Object.defineProperty(BackgroundGeolocation, "LOG_LEVEL_VERBOSE", {740 get: function () { return LOG_LEVEL_VERBOSE; },741 enumerable: false,742 configurable: true743 });744 Object.defineProperty(BackgroundGeolocation, "ACTIVITY_TYPE_OTHER", {745 get: function () { return ACTIVITY_TYPE_OTHER; },746 enumerable: false,747 configurable: true748 });749 Object.defineProperty(BackgroundGeolocation, "ACTIVITY_TYPE_AUTOMOTIVE_NAVIGATION", {750 get: function () { return ACTIVITY_TYPE_AUTOMOTIVE_NAVIGATION; },751 enumerable: false,752 configurable: true753 });754 Object.defineProperty(BackgroundGeolocation, "ACTIVITY_TYPE_FITNESS", {755 get: function () { return ACTIVITY_TYPE_FITNESS; },756 enumerable: false,757 configurable: true758 });759 Object.defineProperty(BackgroundGeolocation, "ACTIVITY_TYPE_OTHER_NAVIGATION", {760 get: function () { return ACTIVITY_TYPE_OTHER_NAVIGATION; },761 enumerable: false,762 configurable: true763 });764 Object.defineProperty(BackgroundGeolocation, "DESIRED_ACCURACY_NAVIGATION", {765 get: function () { return DESIRED_ACCURACY_NAVIGATION; },766 enumerable: false,767 configurable: true768 });769 Object.defineProperty(BackgroundGeolocation, "DESIRED_ACCURACY_HIGH", {770 get: function () { return DESIRED_ACCURACY_HIGH; },771 enumerable: false,772 configurable: true773 });774 Object.defineProperty(BackgroundGeolocation, "DESIRED_ACCURACY_MEDIUM", {775 get: function () { return DESIRED_ACCURACY_MEDIUM; },776 enumerable: false,777 configurable: true778 });779 Object.defineProperty(BackgroundGeolocation, "DESIRED_ACCURACY_LOW", {780 get: function () { return DESIRED_ACCURACY_LOW; },781 enumerable: false,782 configurable: true783 });784 Object.defineProperty(BackgroundGeolocation, "DESIRED_ACCURACY_VERY_LOW", {785 get: function () { return DESIRED_ACCURACY_VERY_LOW; },786 enumerable: false,787 configurable: true788 });789 Object.defineProperty(BackgroundGeolocation, "DESIRED_ACCURACY_LOWEST", {790 get: function () { return DESIRED_ACCURACY_LOWEST; },791 enumerable: false,792 configurable: true793 });794 Object.defineProperty(BackgroundGeolocation, "AUTHORIZATION_STATUS_NOT_DETERMINED", {795 get: function () { return AUTHORIZATION_STATUS_NOT_DETERMINED; },796 enumerable: false,797 configurable: true798 });799 Object.defineProperty(BackgroundGeolocation, "AUTHORIZATION_STATUS_RESTRICTED", {800 get: function () { return AUTHORIZATION_STATUS_RESTRICTED; },801 enumerable: false,802 configurable: true803 });804 Object.defineProperty(BackgroundGeolocation, "AUTHORIZATION_STATUS_DENIED", {805 get: function () { return AUTHORIZATION_STATUS_DENIED; },806 enumerable: false,807 configurable: true808 });809 Object.defineProperty(BackgroundGeolocation, "AUTHORIZATION_STATUS_ALWAYS", {810 get: function () { return AUTHORIZATION_STATUS_ALWAYS; },811 enumerable: false,812 configurable: true813 });814 Object.defineProperty(BackgroundGeolocation, "AUTHORIZATION_STATUS_WHEN_IN_USE", {815 get: function () { return AUTHORIZATION_STATUS_WHEN_IN_USE; },816 enumerable: false,817 configurable: true818 });819 Object.defineProperty(BackgroundGeolocation, "NOTIFICATION_PRIORITY_DEFAULT", {820 get: function () { return NOTIFICATION_PRIORITY_DEFAULT; },821 enumerable: false,822 configurable: true823 });824 Object.defineProperty(BackgroundGeolocation, "NOTIFICATION_PRIORITY_HIGH", {825 get: function () { return NOTIFICATION_PRIORITY_HIGH; },826 enumerable: false,827 configurable: true828 });829 Object.defineProperty(BackgroundGeolocation, "NOTIFICATION_PRIORITY_LOW", {830 get: function () { return NOTIFICATION_PRIORITY_LOW; },831 enumerable: false,832 configurable: true833 });834 Object.defineProperty(BackgroundGeolocation, "NOTIFICATION_PRIORITY_MAX", {835 get: function () { return NOTIFICATION_PRIORITY_MAX; },836 enumerable: false,837 configurable: true838 });839 Object.defineProperty(BackgroundGeolocation, "NOTIFICATION_PRIORITY_MIN", {840 get: function () { return NOTIFICATION_PRIORITY_MIN; },841 enumerable: false,842 configurable: true843 });844 Object.defineProperty(BackgroundGeolocation, "LOCATION_AUTHORIZATION_ALWAYS", {845 get: function () { return LOCATION_AUTHORIZATION_ALWAYS; },846 enumerable: false,847 configurable: true848 });849 Object.defineProperty(BackgroundGeolocation, "LOCATION_AUTHORIZATION_WHEN_IN_USE", {850 get: function () { return LOCATION_AUTHORIZATION_WHEN_IN_USE; },851 enumerable: false,852 configurable: true853 });854 Object.defineProperty(BackgroundGeolocation, "LOCATION_AUTHORIZATION_ANY", {855 get: function () { return LOCATION_AUTHORIZATION_ANY; },856 enumerable: false,857 configurable: true858 });859 Object.defineProperty(BackgroundGeolocation, "PERSIST_MODE_ALL", {860 get: function () { return PERSIST_MODE_ALL; },861 enumerable: false,862 configurable: true863 });864 Object.defineProperty(BackgroundGeolocation, "PERSIST_MODE_LOCATION", {865 get: function () { return PERSIST_MODE_LOCATION; },866 enumerable: false,867 configurable: true868 });869 Object.defineProperty(BackgroundGeolocation, "PERSIST_MODE_GEOFENCE", {870 get: function () { return PERSIST_MODE_GEOFENCE; },871 enumerable: false,872 configurable: true873 });874 Object.defineProperty(BackgroundGeolocation, "PERSIST_MODE_NONE", {875 get: function () { return PERSIST_MODE_NONE; },876 enumerable: false,877 configurable: true878 });879 Object.defineProperty(BackgroundGeolocation, "ACCURACY_AUTHORIZATION_FULL", {880 get: function () { return ACCURACY_AUTHORIZATION_FULL; },881 enumerable: false,882 configurable: true883 });884 Object.defineProperty(BackgroundGeolocation, "ACCURACY_AUTHORIZATION_REDUCED", {885 get: function () { return ACCURACY_AUTHORIZATION_REDUCED; },886 enumerable: false,887 configurable: true888 });889 Object.defineProperty(BackgroundGeolocation, "logger", {890 get: function () { return Logger; },891 enumerable: false,892 configurable: true893 });894 Object.defineProperty(BackgroundGeolocation, "deviceSettings", {895 get: function () { return DeviceSettings; },896 enumerable: false,897 configurable: true898 });899 BackgroundGeolocation.ready = function (config) {900 return NativeModule$3.ready({ options: validateConfig(config) });901 };902 BackgroundGeolocation.reset = function (config) {903 return NativeModule$3.reset({ options: validateConfig(config) });904 };905 BackgroundGeolocation.start = function () {906 return NativeModule$3.start();907 };908 BackgroundGeolocation.stop = function () {909 return NativeModule$3.stop();910 };911 BackgroundGeolocation.startSchedule = function () {912 return NativeModule$3.startSchedule();913 };914 BackgroundGeolocation.stopSchedule = function () {915 return NativeModule$3.stopSchedule();916 };917 BackgroundGeolocation.startGeofences = function () {918 return NativeModule$3.startGeofences();919 };920 BackgroundGeolocation.setConfig = function (config) {921 return NativeModule$3.setConfig({ options: validateConfig(config) });922 };923 BackgroundGeolocation.getState = function () {924 return NativeModule$3.getState();925 };926 BackgroundGeolocation.changePace = function (isMoving) {927 return new Promise(function (resolve, reject) {928 NativeModule$3.changePace({ isMoving: isMoving }).then(function () {929 resolve();930 }).catch(function (error) {931 reject(error.errorMessage);932 });933 });934 };935 BackgroundGeolocation.getCurrentPosition = function (options) {936 return new Promise(function (resolve, reject) {937 NativeModule$3.getCurrentPosition(options).then(function (result) {938 resolve(result);939 }).catch(function (error) {940 reject(error.code);941 });942 });943 };944 BackgroundGeolocation.watchPosition = function (onLocation, onError, options) {945 var _this = this;946 options = options || {};947 return new Promise(function (resolve, reject) { return __awaiter(_this, void 0, void 0, function () {948 var handler, listener;949 return __generator(this, function (_a) {950 switch (_a.label) {951 case 0:952 handler = function (response) {953 if (response.hasOwnProperty("error") && (response.error != null)) {954 if (typeof (onError) === 'function') {955 onError(response.error.code);956 }957 else {958 console.warn('[BackgroundGeolocation watchPostion] DEFAULT ERROR HANDLER. Provide an onError handler to watchPosition to receive this message: ', response.error);959 }960 }961 else {962 onLocation(response);963 }964 };965 return [4 /*yield*/, NativeModule$3.addListener("watchposition", handler)];966 case 1:967 listener = _a.sent();968 NativeModule$3.watchPosition({ options: options }).then(function () {969 WATCH_POSITION_SUBSCRIPTIONS.push(listener);970 resolve();971 }).catch(function (error) {972 listener.remove();973 reject(error.message);974 });975 return [2 /*return*/];976 }977 });978 }); });979 };980 BackgroundGeolocation.stopWatchPosition = function () {981 for (var n = 0; n < WATCH_POSITION_SUBSCRIPTIONS.length; n++) {982 var subscription = WATCH_POSITION_SUBSCRIPTIONS[n];983 subscription.remove();984 }985 return NativeModule$3.stopWatchPosition();986 };987 BackgroundGeolocation.requestPermission = function () {988 return new Promise(function (resolve, reject) {989 NativeModule$3.requestPermission().then(function (result) {990 if (result.success) {991 resolve(result.status);992 }993 else {994 reject(result.status);995 }996 });997 });998 };999 BackgroundGeolocation.requestTemporaryFullAccuracy = function (purpose) {1000 return new Promise(function (resolve, reject) {1001 NativeModule$3.requestTemporaryFullAccuracy({ purpose: purpose }).then(function (result) {1002 resolve(result.accuracyAuthorization);1003 }).catch(function (error) {1004 reject(error.message);1005 });1006 });1007 };1008 BackgroundGeolocation.getProviderState = function () {1009 return NativeModule$3.getProviderState();1010 };1011 /// Locations database1012 ///1013 BackgroundGeolocation.getLocations = function () {1014 return new Promise(function (resolve, reject) {1015 NativeModule$3.getLocations().then(function (result) {1016 resolve(result.locations);1017 }).catch(function (error) {1018 reject(error.message);1019 });1020 });1021 };1022 BackgroundGeolocation.insertLocation = function (params) {1023 return new Promise(function (resolve, reject) {1024 NativeModule$3.insertLocation({ options: params }).then(function (result) {1025 resolve(result.uuid);1026 }).catch(function (error) {1027 reject(error.message);1028 });1029 });1030 };1031 BackgroundGeolocation.destroyLocations = function () {1032 return new Promise(function (resolve, reject) {1033 NativeModule$3.destroyLocations().then(function () {1034 resolve();1035 }).catch(function (error) {1036 reject(error.message);1037 });1038 });1039 };1040 BackgroundGeolocation.destroyLocation = function (uuid) {1041 return new Promise(function (resolve, reject) {1042 NativeModule$3.destroyLocation({ uuid: uuid }).then(function () {1043 resolve();1044 }).catch(function (error) {1045 reject(error.message);1046 });1047 });1048 };1049 BackgroundGeolocation.getCount = function () {1050 return new Promise(function (resolve, reject) {1051 NativeModule$3.getCount().then(function (result) {1052 resolve(result.count);1053 }).catch(function (error) {1054 reject(error.message);1055 });1056 });1057 };1058 BackgroundGeolocation.sync = function () {1059 return new Promise(function (resolve, reject) {1060 NativeModule$3.sync().then(function (result) {1061 resolve(result.locations);1062 }).catch(function (error) {1063 reject(error.message);1064 });1065 });1066 };1067 /// Geofencing1068 ///1069 BackgroundGeolocation.addGeofence = function (params) {1070 return new Promise(function (resolve, reject) {1071 NativeModule$3.addGeofence({ options: params }).then(function () {1072 resolve();1073 }).catch(function (error) {1074 reject(error.message);1075 });1076 });1077 };1078 BackgroundGeolocation.addGeofences = function (params) {1079 return new Promise(function (resolve, reject) {1080 NativeModule$3.addGeofences({ options: params }).then(function () {1081 resolve();1082 }).catch(function (error) {1083 reject(error.message);1084 });1085 });1086 };1087 BackgroundGeolocation.getGeofences = function () {1088 return new Promise(function (resolve, reject) {1089 NativeModule$3.getGeofences().then(function (result) {1090 resolve(result.geofences);1091 }).catch(function (error) {1092 reject(error.message);1093 });1094 });1095 };1096 BackgroundGeolocation.getGeofence = function (identifier) {1097 return new Promise(function (resolve, reject) {1098 if (identifier === null) {1099 reject('identifier is null');1100 return;1101 }1102 NativeModule$3.getGeofence({ identifier: identifier }).then(function (result) {1103 resolve(result);1104 }).catch(function (error) {1105 reject(error.message);1106 });1107 });1108 };1109 BackgroundGeolocation.geofenceExists = function (identifier) {1110 return new Promise(function (resolve, reject) {1111 if (identifier === null) {1112 reject('identifier is null');1113 return;1114 }1115 NativeModule$3.geofenceExists({ identifier: identifier }).then(function (result) {1116 resolve(result.exists);1117 }).catch(function (error) {1118 reject(error.message);1119 });1120 });1121 };1122 BackgroundGeolocation.removeGeofence = function (identifier) {1123 return new Promise(function (resolve, reject) {1124 if (identifier === null) {1125 reject('identifier is null');1126 return;1127 }1128 NativeModule$3.removeGeofence({ identifier: identifier }).then(function () {1129 resolve();1130 }).catch(function (error) {1131 reject(error.message);1132 });1133 });1134 };1135 BackgroundGeolocation.removeGeofences = function (identifiers) {1136 identifiers = identifiers || [];1137 return new Promise(function (resolve, reject) {1138 NativeModule$3.removeGeofences({ identifiers: identifiers }).then(function () {1139 resolve();1140 }).catch(function (error) {1141 reject(error.message);1142 });1143 });1144 };1145 /// Odometer1146 ///1147 BackgroundGeolocation.getOdometer = function () {1148 return new Promise(function (resolve, reject) {1149 NativeModule$3.getOdometer().then(function (result) {1150 resolve(result.odometer);1151 }).catch(function (error) {1152 reject(error.message);1153 });1154 });1155 };1156 BackgroundGeolocation.setOdometer = function (value) {1157 return new Promise(function (resolve, reject) {1158 NativeModule$3.setOdometer({ "odometer": value }).then(function (result) {1159 resolve(result);1160 }).catch(function (error) {1161 reject(error.message);1162 });1163 });1164 };1165 BackgroundGeolocation.resetOdometer = function () {1166 return BackgroundGeolocation.setOdometer(0);1167 };1168 /// Background Tasks1169 ///1170 BackgroundGeolocation.startBackgroundTask = function () {1171 return new Promise(function (resolve, reject) {1172 NativeModule$3.startBackgroundTask().then(function (result) {1173 resolve(result.taskId);1174 }).catch(function (error) {1175 reject(error.message);1176 });1177 });1178 };1179 BackgroundGeolocation.stopBackgroundTask = function (taskId) {1180 return new Promise(function (resolve, reject) {1181 NativeModule$3.stopBackgroundTask({ taskId: taskId }).then(function () {1182 resolve();1183 }).catch(function (error) {1184 reject(error.message);1185 });1186 });1187 };1188 /// @alias stopBackgroundTask1189 BackgroundGeolocation.finish = function (taskId) {1190 return BackgroundGeolocation.stopBackgroundTask(taskId);1191 };1192 BackgroundGeolocation.getDeviceInfo = function () {1193 return NativeModule$3.getDeviceInfo();1194 };1195 BackgroundGeolocation.playSound = function (soundId) {1196 return NativeModule$3.playSound({ soundId: soundId });1197 };1198 BackgroundGeolocation.isPowerSaveMode = function () {1199 return new Promise(function (resolve, reject) {1200 NativeModule$3.isPowerSaveMode().then(function (result) {1201 resolve(result.isPowerSaveMode);1202 }).catch(function (error) {1203 reject(error.message);1204 });1205 });1206 };1207 BackgroundGeolocation.getSensors = function () {1208 return NativeModule$3.getSensors();1209 };1210 /// TransistorAuthorizationToken1211 ///1212 BackgroundGeolocation.findOrCreateTransistorAuthorizationToken = function (orgname, username, url) {1213 return TransistorAuthorizationToken.findOrCreate(orgname, username, url);1214 };1215 BackgroundGeolocation.destroyTransistorAuthorizationToken = function (url) {1216 return TransistorAuthorizationToken.destroy(url);1217 };1218 /// Event Handling1219 ///1220 BackgroundGeolocation.onLocation = function (success, failure) {1221 return BackgroundGeolocation.addListener(Events.LOCATION, success, failure);1222 };1223 BackgroundGeolocation.onMotionChange = function (success) {1224 return BackgroundGeolocation.addListener(Events.MOTIONCHANGE, success);1225 };1226 BackgroundGeolocation.onHttp = function (success) {1227 return BackgroundGeolocation.addListener(Events.HTTP, success);1228 };1229 BackgroundGeolocation.onHeartbeat = function (success) {1230 return BackgroundGeolocation.addListener(Events.HEARTBEAT, success);1231 };1232 BackgroundGeolocation.onProviderChange = function (success) {1233 return BackgroundGeolocation.addListener(Events.PROVIDERCHANGE, success);1234 };1235 BackgroundGeolocation.onActivityChange = function (success) {1236 return BackgroundGeolocation.addListener(Events.ACTIVITYCHANGE, success);1237 };1238 BackgroundGeolocation.onGeofence = function (success) {1239 return BackgroundGeolocation.addListener(Events.GEOFENCE, success);1240 };1241 BackgroundGeolocation.onGeofencesChange = function (success) {1242 return BackgroundGeolocation.addListener(Events.GEOFENCESCHANGE, success);1243 };1244 BackgroundGeolocation.onSchedule = function (success) {1245 return BackgroundGeolocation.addListener(Events.SCHEDULE, success);1246 };1247 BackgroundGeolocation.onEnabledChange = function (success) {1248 return BackgroundGeolocation.addListener(Events.ENABLEDCHANGE, success);1249 };1250 BackgroundGeolocation.onConnectivityChange = function (success) {1251 return BackgroundGeolocation.addListener(Events.CONNECTIVITYCHANGE, success);1252 };1253 BackgroundGeolocation.onPowerSaveChange = function (success) {1254 return BackgroundGeolocation.addListener(Events.POWERSAVECHANGE, success);1255 };1256 BackgroundGeolocation.onNotificationAction = function (success) {1257 return BackgroundGeolocation.addListener(Events.NOTIFICATIONACTION, success);1258 };1259 BackgroundGeolocation.onAuthorization = function (success) {1260 return BackgroundGeolocation.addListener(Events.AUTHORIZATION, success);1261 };1262 ///1263 /// Listen to a plugin event1264 ///1265 BackgroundGeolocation.addListener = function (event, success, failure) {1266 if (!Events[event.toUpperCase()]) {1267 throw (TAG + "#addListener - Unknown event '" + event + "'");1268 }1269 var handler = function (response) {1270 if (response.hasOwnProperty("value")) {1271 response = response.value;1272 }1273 if (response.hasOwnProperty("error") && (response.error != null)) {1274 if (typeof (failure) === 'function') {1275 failure(response.error);1276 }1277 else {1278 success(response);1279 }1280 }1281 else {1282 success(response);1283 }1284 };1285 // Create a flag to capture edge-case where the developer subscribes to an event then IMMEDIATELY calls subscription.remove()1286 // before NativeModule.addListener has resolved.1287 // The developer would have to do something weird like this:1288 // const subscription = BackgroundGeolocation.onLocation(this.onLocation);1289 // subscription.remove();1290 //1291 // The reason for this is I don't want developers to have to await calls to BackgroundGeolocation.onXXX(myHandler).1292 //1293 var isRemoved = false;1294 var subscriptionProxy = {1295 remove: function () {1296 // EmptyFn until NativeModule.addListener resolves and re-writes this function1297 isRemoved = true;1298 console.warn('[BackgroundGeolocation.addListener] Unexpected call to subscription.remove() on subscriptionProxy. Waiting for NativeModule.addListener to resolve.');1299 }1300 };1301 // Now add the listener and re-write subscriptionProxy.remove.1302 NativeModule$3.addListener(event, handler).then(function (listener) {1303 var subscription = new Subscription(event, listener, success);1304 EVENT_SUBSCRIPTIONS.push(subscription);1305 subscriptionProxy.remove = function () {1306 listener.remove();1307 // Remove from EVENT_SUBSCRIPTIONS.1308 if (EVENT_SUBSCRIPTIONS.indexOf(subscription) >= 0) {1309 EVENT_SUBSCRIPTIONS.splice(EVENT_SUBSCRIPTIONS.indexOf(subscription), 1);1310 }1311 };1312 if (isRemoved) {1313 // Caught edge-case. Developer added an event-handler then immediately call subscription.remove().1314 subscriptionProxy.remove();1315 }1316 });1317 return subscriptionProxy;1318 };1319 BackgroundGeolocation.removeListener = function (event, callback) {1320 console.warn('BackgroundGeolocation.removeListener is deprecated. Event-listener methods (eg: onLocation) now return a Subscription instance. Call subscription.remove() on the returned subscription instead. Eg:\nconst subscription = BackgroundGeolocation.onLocation(myLocationHandler)\n...\nsubscription.remove()');1321 return new Promise(function (resolve, reject) {1322 var found = null;1323 for (var n = 0, len = EVENT_SUBSCRIPTIONS.length; n < len; n++) {1324 var sub = EVENT_SUBSCRIPTIONS[n];1325 if ((sub.event === event) && (sub.callback === callback)) {1326 found = sub;1327 break;1328 }1329 }1330 if (found !== null) {1331 EVENT_SUBSCRIPTIONS.splice(EVENT_SUBSCRIPTIONS.indexOf(found), 1);1332 found.subscription.remove();1333 resolve();1334 }1335 else {1336 console.warn(TAG + ' Failed to find listener for event ' + event);1337 reject();1338 }1339 });1340 };1341 BackgroundGeolocation.removeListeners = function () {1342 var _this = this;1343 return new Promise(function (resolve) { return __awaiter(_this, void 0, void 0, function () {1344 return __generator(this, function (_a) {1345 switch (_a.label) {1346 case 0:1347 EVENT_SUBSCRIPTIONS = [];1348 return [4 /*yield*/, NativeModule$3.removeAllEventListeners()];1349 case 1:1350 _a.sent();1351 resolve();1352 return [2 /*return*/];1353 }1354 });1355 }); });1356 };1357 return BackgroundGeolocation;1358}());1359var tracking;1360(function (tracking) {1361 function restart() {1362 if (window.cordova) {1363 clean();1364 gps.showActivationMsg(true, false);1365 }1366 else {1367 msg.danger(util.translate('tracking.usingPC'));1368 }1369 }1370 tracking.restart = restart;1371 async function initiate() {1372 if (window.cordova) {1373 let api = new Webapi();1374 const confToken = (await storage.get('confToken'));1375 const auth = (await api.connect());1376 const trackingData = confToken.tracking;1377 const appName = (await storage.get('flexyApp')).Title;1378 const scheduled = trackingData && trackingData.schedule && trackingData.schedule.length > 0;1379 BackgroundGeolocation.onSchedule(async () => {1380 if (trackingData.holidays.includes(moment().format('YYYY/MM/DD'))) {1381 BackgroundGeolocation.stop();1382 }1383 });1384 BackgroundGeolocation.ready({1385 enableHeadless: true,1386 authorization: {1387 strategy: "JWT",1388 accessToken: auth.bearerToken1389 },1390 httpRootProperty: 'Locations',1391 url: (auth.url + '/webapi/exec/SendLocationData'),1392 params: { "UserId": confToken.user.currentUserId },1393 batchSync: true,1394 maxBatchSize: 20,1395 autoSync: true,1396 notificationTitle: appName + util.translate('tracking.notificationTitle'),1397 notificationText: util.translate('tracking.notificationText') + appName,1398 stationaryRadius: 25,1399 distanceFilter: (trackingData.radius ? trackingData.radius : 50),1400 desiredAccuracy: BackgroundGeolocation.DESIRED_ACCURACY_HIGH,1401 debug: false,1402 startOnBoot: true,1403 stopOnTerminate: false,1404 stopOnStationary: false,1405 stopTimeout: 15,1406 //logLevel: 0,1407 schedule: (scheduled ? trackingData.schedule : [])1408 }).then(async (state) => {1409 if (!state.enabled) {1410 if (scheduled)1411 BackgroundGeolocation.startSchedule();1412 else1413 BackgroundGeolocation.start();1414 }1415 else if (scheduled && !state.schedulerEnabled) {1416 BackgroundGeolocation.startSchedule();1417 }1418 });1419 }1420 else {1421 msg.danger(util.translate('tracking.usingPC'));1422 }1423 }1424 tracking.initiate = initiate;1425 async function syncLocations() {1426 BackgroundGeolocation.sync().then((res) => {1427 console.log(res);1428 }).catch((err) => {1429 console.log(JSON.parse(err));1430 });1431 }1432 tracking.syncLocations = syncLocations;1433 async function checkLogs() {1434 console.log(await BackgroundGeolocation.logger.getLog());1435 }1436 tracking.checkLogs = checkLogs;1437 async function checkState() {1438 if (window.cordova) {1439 console.log(await BackgroundGeolocation.getState());1440 }1441 else {1442 msg.danger(util.translate('tracking.usingPC'));1443 }1444 }1445 tracking.checkState = checkState;1446 function clean() {1447 if (window.cordova) {1448 BackgroundGeolocation.stop();1449 }1450 else {1451 msg.danger(util.translate('tracking.usingPC'));1452 }1453 }1454 tracking.clean = clean;1455 async function getLocations() {1456 if (window.cordova) {1457 return await BackgroundGeolocation.getLocations();1458 }1459 else {1460 msg.danger(util.translate('tracking.usingPC'));1461 }1462 }1463 tracking.getLocations = getLocations;1464 /*export function getSchedule(trackingCnf:TrackingConfig) {1465 let weekDates:Array<String> = util.getNextSevenDates()1466 1467 var holidays = [];1468 weekDates.forEach(day => {1469 if (trackingCnf.holidays.includes(day)) {1470 holidays.push(moment(day).day() + 1);1471 }1472 });1473 var schedule = [];1474 if (trackingCnf.schedule[0] && !holidays.includes(1)) schedule.push(trackingCnf.schedule[0]);1475 if (trackingCnf.schedule[1] && !holidays.includes(2)) schedule.push(trackingCnf.schedule[1]);1476 if (trackingCnf.schedule[2] && !holidays.includes(3)) schedule.push(trackingCnf.schedule[2]);1477 if (trackingCnf.schedule[3] && !holidays.includes(4)) schedule.push(trackingCnf.schedule[3]);1478 if (trackingCnf.schedule[4] && !holidays.includes(5)) schedule.push(trackingCnf.schedule[4]);1479 if (trackingCnf.schedule[5] && !holidays.includes(6)) schedule.push(trackingCnf.schedule[5]);1480 if (trackingCnf.schedule[6] && !holidays.includes(7)) schedule.push(trackingCnf.schedule[6]);1481 return schedule;1482 }*/1483})(tracking || (tracking = {}));1484var gps;1485(function (gps) {1486 let locationAccuracy = new LocationAccuracy;1487 let diagnostic = new Diagnostic;1488 let actBackLocation = false;1489 let deniedAcces = false;1490 /* alert('position.coords.latitude: ' + position.coords.latitude + '\n' +1491 'position.coords.longitude: ' + position.coords.longitude + '\n' +1492 'position.coords.altitude: ' + position.coords.altitude + '\n' +1493 'position.coords.accuracy: ' + position.coords.accuracy + '\n' +1494 'position.coords.altitudeAccuracy: ' + position.coords.altitudeAccuracy + '\n' +1495 'position.coords.heading: ' + position.coords.heading + '\n' +1496 'position.coords.speed: ' + position.coords.speed + '\n' +1497 'position.timestamp: ' + position.timestamp + '\n');1498 */1499 async function getCoords(geoTimeout = 10000, maximumAge = 10) {1500 return new Promise(async (resolve, reject) => {1501 var geoOpt = { maximumAge: maximumAge, timeout: geoTimeout, enableHighAccuracy: true };1502 let id = navigator.geolocation.watchPosition((pos) => {1503 navigator.geolocation.clearWatch(id);1504 resolve(pos);1505 }, (err) => {1506 getCoordsError(err);1507 navigator.geolocation.clearWatch(id);1508 reject(err);1509 throw err;1510 }, geoOpt);1511 });1512 }1513 gps.getCoords = getCoords;1514 function getCoordsError(error) {1515 if (error.code == 3) {1516 msg.danger(util.translate('exceptions.gpstimeout'));1517 }1518 else {1519 alert('code: ' + error.code + '\n' +1520 'message: ' + error.message + '\n');1521 }1522 }1523 function requestGPSPermission(actMsg) {1524 diagnostic.requestLocationAuthorization(diagnostic.locationAuthorizationMode.ALWAYS).then(async (result) => {1525 let openNativeSettings = new OpenNativeSettings;1526 switch (result) {1527 case diagnostic.permissionStatus.DENIED_ALWAYS:1528 openNativeSettings.open('application_details').then(async () => {1529 if (await diagnostic.isLocationAuthorized())1530 askToTurnOnGPS(actMsg);1531 if (await diagnostic.isLocationAuthorized())1532 askToTurnOnGPS(actMsg);1533 if (await diagnostic.isLocationAuthorized())1534 askToTurnOnGPS(actMsg);1535 });1536 break;1537 case diagnostic.permissionStatus.GRANTED:1538 askToTurnOnGPS(actMsg);1539 break;1540 case diagnostic.permissionStatus.GRANTED_WHEN_IN_USE:1541 if (cordova.platformId === 'ios') {1542 openNativeSettings.open('application_details').then(async () => {1543 if (await diagnostic.isLocationAuthorized())1544 askToTurnOnGPS(actMsg);1545 });1546 break;1547 }1548 if (actBackLocation) {1549 if (deniedAcces) {1550 openNativeSettings.open('location').then(async () => {1551 diagnostic.getLocationAuthorizationStatus().then((result) => {1552 if (result === diagnostic.permissionStatus.GRANTED) {1553 askToTurnOnGPS(actMsg);1554 deniedAcces = false;1555 }1556 });1557 });1558 }1559 else1560 deniedAcces = true;1561 }1562 else1563 util.translate('gps.granted');1564 break;1565 }1566 }, err => { if (err.code !== 4)1567 msg.showError('Error requesting location permissions: ' + err.message); });1568 }1569 function askToTurnOnGPS(actMsg) {1570 locationAccuracy.request(locationAccuracy.REQUEST_PRIORITY_HIGH_ACCURACY).then(async () => {1571 actMsg.dismiss();1572 util.translate('gps.granted');1573 let token = await storage.get('confToken');1574 token.user.backLocationAccepted = true;1575 storage.set('confToken', token);1576 if (actBackLocation) {1577 tracking.clean();1578 tracking.initiate();1579 }1580 }, err => { if (err.code !== 4)1581 msg.showError('Error requesting location permissions: ' + err.message); });1582 }1583 function showActivationMsg(activateBackLocation, permissionRequest) {1584 if (!permissionRequest) {1585 getActivationMsg(null, permissionRequest);1586 }1587 else {1588 actBackLocation = activateBackLocation;1589 diagnostic.getLocationAuthorizationStatus().then((result) => {1590 switch (result) {1591 case diagnostic.permissionStatus.GRANTED:1592 getActivationMsg(true, permissionRequest);1593 break;1594 case diagnostic.permissionStatus.GRANTED_WHEN_IN_USE:1595 if (actBackLocation)1596 getActivationMsg(false, permissionRequest);1597 else1598 getActivationMsg(true, permissionRequest);1599 break;1600 default:1601 getActivationMsg(false, permissionRequest);1602 break;1603 }1604 }, (err) => { msg.showError('Error requesting location permissions: ' + err); });1605 }1606 }1607 gps.showActivationMsg = showActivationMsg;1608 async function getActivationMsg(permission, permissionRequest) {1609 let shown = await storage.get('trackingMsgShown');1610 if ((!shown && !permissionRequest) || ((!permission || await gpsOff()) && permissionRequest)) {1611 storage.set('trackingMsgShown', true);1612 const actMsg = document.createElement('ion-alert');1613 actMsg.header = util.translate('gps.activationMsg');1614 actMsg.message = util.translate('gps.activationSubmsg');1615 actMsg.backdropDismiss = false;1616 actMsg.buttons = [1617 {1618 text: util.translate('gps.policy'),1619 handler: () => {1620 window.location.href = "https://www.flexygo.com/politica-de-privacidad-flexygo-mobile/";1621 return false;1622 }1623 },1624 {1625 text: (permissionRequest ? util.translate('gps.activate') : util.translate('msg.ok')),1626 handler: () => {1627 if (!permissionRequest)1628 return;1629 if (permission)1630 askToTurnOnGPS(actMsg);1631 else1632 requestGPSPermission(actMsg);1633 return false;1634 }1635 }1636 ];1637 document.body.appendChild(actMsg);1638 actMsg.present();1639 }1640 else if (permissionRequest && actBackLocation) {1641 tracking.initiate();1642 }1643 }1644 async function gpsOff() {1645 if (cordova.platformId === 'ios') {1646 return await locationAccuracy.canRequest();1647 }1648 else {1649 let mode = await diagnostic.getLocationMode();1650 if (mode === diagnostic.locationMode.LOCATION_OFF)1651 return true;1652 else1653 return false;1654 }1655 }1656})(gps || (gps = {}));...

Full Screen

Full Screen

controller.js

Source:controller.js Github

copy

Full Screen

1// Test dependencies are required and exposed in common/bootstrap.js2require('../common/bootstrap');3function newTessel(options) {4 var tessel = new Tessel({5 authorized: options.authorized !== undefined ? options.authorized : true,6 connectionType: options.connectionType || 'LAN',7 end() {8 return (options.end && options.end()) || Promise.resolve();9 }10 });11 tessel.name = options.name || 'a';12 options.sandbox.stub(tessel, 'close').callsFake(function() {13 return Promise.resolve();14 });15 return tessel;16}17exports['controller.tessel'] = {18 setUp(done) {19 this.sandbox = sinon.sandbox.create();20 this.warn = this.sandbox.stub(log, 'warn');21 this.info = this.sandbox.stub(log, 'info');22 this.basic = this.sandbox.stub(log, 'basic');23 this.error = this.sandbox.stub(log, 'error');24 done();25 },26 tearDown(done) {27 this.sandbox.restore();28 controller.tessel = null;29 done();30 },31 tesselStartsNull(test) {32 test.expect(1);33 test.equal(controller.tessel, null);34 test.done();35 },36};37exports['controller.setupLocal'] = {38 setUp(done) {39 this.sandbox = sinon.sandbox.create();40 this.warn = this.sandbox.stub(log, 'warn');41 this.info = this.sandbox.stub(log, 'info');42 this.basic = this.sandbox.stub(log, 'basic');43 this.error = this.sandbox.stub(log, 'error');44 this.provisionsetupLocal = this.sandbox.stub(provision, 'setupLocal');45 done();46 },47 tearDown(done) {48 this.sandbox.restore();49 done();50 },51 passthroughCall(test) {52 test.expect(2);53 var options = {};54 controller.setupLocal(options);55 test.equal(this.provisionsetupLocal.callCount, 1);56 test.equal(this.provisionsetupLocal.lastCall.args[0], options);57 test.done();58 },59};60exports['controller.reconcileTessels'] = {61 setUp(done) {62 this.sandbox = sinon.sandbox.create();63 this.spinnerStart = this.sandbox.stub(log.spinner, 'start');64 this.spinnerStop = this.sandbox.stub(log.spinner, 'stop');65 this.warn = this.sandbox.stub(log, 'warn');66 this.info = this.sandbox.stub(log, 'info');67 this.basic = this.sandbox.stub(log, 'basic');68 this.error = this.sandbox.stub(log, 'error');69 done();70 },71 tearDown(done) {72 this.sandbox.restore();73 done();74 },75 resolveImmediatelyWhenOnlyOne(test) {76 test.expect(1);77 controller.reconcileTessels([1]).then(reconciled => {78 test.equal(reconciled, 1);79 test.done();80 });81 },82};83exports['controller.provision'] = {84 setUp(done) {85 this.sandbox = sinon.sandbox.create();86 this.spinnerStart = this.sandbox.stub(log.spinner, 'start');87 this.spinnerStop = this.sandbox.stub(log.spinner, 'stop');88 this.warn = this.sandbox.stub(log, 'warn');89 this.info = this.sandbox.stub(log, 'info');90 this.basic = this.sandbox.stub(log, 'basic');91 this.error = this.sandbox.stub(log, 'error');92 this.isProvisioned = this.sandbox.stub(Tessel, 'isProvisioned').returns(true);93 this.standardTesselCommand = this.sandbox.stub(controller, 'standardTesselCommand').returns(Promise.resolve());94 done();95 },96 tearDown(done) {97 this.sandbox.restore();98 done();99 },100 isProvisionedAndOptsNotForced(test) {101 test.expect(1);102 controller.provision({}).then(() => {103 // We only care that this resolves.104 test.ok(true);105 test.done();106 });107 },108};109exports['controller.closeTesselConnections'] = {110 setUp(done) {111 this.sandbox = sinon.sandbox.create();112 this.spinnerStart = this.sandbox.stub(log.spinner, 'start');113 this.spinnerStop = this.sandbox.stub(log.spinner, 'stop');114 this.warn = this.sandbox.stub(log, 'warn');115 this.info = this.sandbox.stub(log, 'info');116 this.basic = this.sandbox.stub(log, 'basic');117 this.error = this.sandbox.stub(log, 'error');118 done();119 },120 tearDown(done) {121 this.sandbox.restore();122 done();123 },124 rejectsOnError(test) {125 test.expect(1);126 this.asyncEach = this.sandbox.stub(async, 'each').callsFake((tessels, next, done) => {127 done(new Error('This is only a test'));128 });129 controller.closeTesselConnections([1, 2, 3])130 .catch(error => {131 test.equal(error.toString(), 'Error: This is only a test');132 test.done();133 });134 },135 callsCloseOnAllAuthorizedLANConnections(test) {136 test.expect(3);137 var a = newTessel({138 sandbox: this.sandbox,139 authorized: true,140 connectionType: 'LAN'141 });142 var b = newTessel({143 sandbox: this.sandbox,144 authorized: true,145 connectionType: 'LAN'146 });147 var c = newTessel({148 sandbox: this.sandbox,149 authorized: false,150 connectionType: 'LAN'151 });152 controller.closeTesselConnections([a, b, c])153 .then(() => {154 test.equal(a.close.callCount, 1);155 test.equal(b.close.callCount, 1);156 test.equal(c.close.callCount, 0);157 test.done();158 });159 },160 callsCloseOnAllUSBConnections(test) {161 test.expect(3);162 var a = newTessel({163 sandbox: this.sandbox,164 connectionType: 'USB'165 });166 var b = newTessel({167 sandbox: this.sandbox,168 connectionType: 'USB'169 });170 var c = newTessel({171 sandbox: this.sandbox,172 authorized: true,173 connectionType: 'LAN'174 });175 controller.closeTesselConnections([a, b, c])176 .then(() => {177 test.equal(a.close.callCount, 1);178 test.equal(b.close.callCount, 1);179 test.equal(c.close.callCount, 1);180 test.done();181 });182 },183 resolvesForUnauthorizedLANConnections(test) {184 test.expect(1);185 var a = newTessel({186 sandbox: this.sandbox,187 authorized: false,188 connectionType: 'LAN'189 });190 controller.closeTesselConnections([a])191 .then(() => {192 test.equal(a.close.callCount, 0);193 test.done();194 });195 },196 resolvesForClosedUSBConnections(test) {197 test.expect(1);198 var a = newTessel({199 sandbox: this.sandbox,200 authorized: false,201 connectionType: 'USB'202 });203 a.usbConnection.closed = true;204 controller.closeTesselConnections([a])205 .then(() => {206 test.equal(a.close.callCount, 0);207 test.done();208 });209 },210};211exports['controller.runHeuristics'] = {212 setUp(done) {213 this.sandbox = sinon.sandbox.create();214 this.spinnerStart = this.sandbox.stub(log.spinner, 'start');215 this.spinnerStop = this.sandbox.stub(log.spinner, 'stop');216 this.warn = this.sandbox.stub(log, 'warn');217 this.info = this.sandbox.stub(log, 'info');218 this.basic = this.sandbox.stub(log, 'basic');219 this.error = this.sandbox.stub(log, 'error');220 this.processOn = this.sandbox.stub(process, 'on');221 done();222 },223 tearDown(done) {224 this.sandbox.restore();225 done();226 },227 oneUSBDevice(test) {228 test.expect(1);229 var a = newTessel({230 sandbox: this.sandbox,231 authorized: true,232 connectionType: 'USB'233 });234 controller.runHeuristics({}, [a])235 .then(function(tessel) {236 test.deepEqual(a, tessel);237 test.done();238 });239 },240 oneLANDevice(test) {241 test.expect(1);242 var a = newTessel({243 sandbox: this.sandbox,244 authorized: true,245 connectionType: 'LAN'246 });247 controller.runHeuristics({}, [a])248 .then(function(tessel) {249 test.deepEqual(a, tessel);250 test.done();251 });252 },253 USBAndLANDevices(test) {254 test.expect(1);255 var a = newTessel({256 name: 'a',257 sandbox: this.sandbox,258 authorized: true,259 connectionType: 'LAN'260 });261 var b = newTessel({262 name: 'b',263 sandbox: this.sandbox,264 authorized: true,265 connectionType: 'USB'266 });267 controller.runHeuristics({}, [a, b])268 .then(function(tessel) {269 // console.log(tessel);270 test.deepEqual(b, tessel);271 test.done();272 }).catch(error => console.log(error));273 },274 USBAndLANDevicesButNamedDeviceIsLateInList(test) {275 test.expect(1);276 var a = newTessel({277 name: 'a',278 sandbox: this.sandbox,279 authorized: true,280 connectionType: 'LAN'281 });282 var b = newTessel({283 name: 'b',284 sandbox: this.sandbox,285 authorized: true,286 connectionType: 'USB'287 });288 var c = newTessel({289 name: 'c',290 sandbox: this.sandbox,291 authorized: true,292 connectionType: 'USB'293 });294 controller.runHeuristics({name: 'c'}, [a, b, c])295 .then(function(tessel) {296 test.deepEqual(c, tessel);297 test.done();298 }).catch(error => console.log(error));299 },300 bothConnectionsAndLAN(test) {301 test.expect(1);302 var a = newTessel({303 sandbox: this.sandbox,304 authorized: true,305 connectionType: 'LAN'306 });307 var b = newTessel({308 sandbox: this.sandbox,309 authorized: true,310 connectionType: 'USB'311 });312 b.addConnection({313 connectionType: 'LAN',314 authorized: true315 });316 controller.runHeuristics({}, [a, b])317 .then(function(tessel) {318 test.deepEqual(b, tessel);319 test.done();320 });321 },322 bothConnectionsAndMultipleLAN(test) {323 test.expect(1);324 var a = newTessel({325 sandbox: this.sandbox,326 authorized: true,327 connectionType: 'LAN'328 });329 var b = newTessel({330 sandbox: this.sandbox,331 authorized: true,332 connectionType: 'LAN'333 });334 var c = newTessel({335 sandbox: this.sandbox,336 authorized: true,337 connectionType: 'USB'338 });339 c.addConnection({340 connectionType: 'LAN',341 authorized: true342 });343 controller.runHeuristics({}, [a, b, c])344 .then(function(tessel) {345 test.deepEqual(c, tessel);346 test.done();347 }).catch(error => console.log(error));348 },349 USBAndLANDevicesWithNameOption(test) {350 test.expect(1);351 var a = newTessel({352 sandbox: this.sandbox,353 authorized: true,354 connectionType: 'LAN',355 name: 'Me!'356 });357 var b = newTessel({358 sandbox: this.sandbox,359 authorized: true,360 connectionType: 'USB',361 name: 'Not Me!'362 });363 controller.runHeuristics({364 name: a.name365 }, [a, b])366 .then(function(tessel) {367 test.deepEqual(a, tessel);368 test.done();369 });370 },371 USBAndLANDevicesWithEnvVariable(test) {372 test.expect(1);373 const winningName = 'Me!';374 process.env['Tessel'] = winningName;375 const a = newTessel({376 sandbox: this.sandbox,377 authorized: true,378 connectionType: 'LAN'379 });380 a.name = winningName;381 const b = newTessel({382 sandbox: this.sandbox,383 authorized: true,384 connectionType: 'USB'385 });386 b.name = `Not ${winningName}`;387 controller.runHeuristics({388 name: a.name389 }, [a, b])390 .then(tessel => {391 test.deepEqual(a, tessel);392 process.env['Tessel'] = undefined;393 test.done();394 });395 },396 catchAmbiguityTwoLAN(test) {397 test.expect(1);398 var a = newTessel({399 sandbox: this.sandbox,400 authorized: true,401 connectionType: 'LAN'402 });403 var b = newTessel({404 sandbox: this.sandbox,405 authorized: true,406 connectionType: 'LAN'407 });408 controller.runHeuristics({}, [a, b])409 .then(() => {410 test.ok(false, 'Test failed because expected HeuristicAmbiguityError did not occur.');411 test.done();412 })413 .catch(error => {414 test.equal(error instanceof controller.HeuristicAmbiguityError, true);415 test.done();416 });417 },418 catchAmbiguityTwoUSB(test) {419 test.expect(1);420 var a = newTessel({421 sandbox: this.sandbox,422 authorized: true,423 connectionType: 'USB'424 });425 var b = newTessel({426 sandbox: this.sandbox,427 authorized: true,428 connectionType: 'USB'429 });430 controller.runHeuristics({}, [a, b])431 .then(() => {432 test.ok(false, 'Test failed because expected HeuristicAmbiguityError did not occur.');433 test.done();434 })435 .catch(error => {436 test.equal(error instanceof controller.HeuristicAmbiguityError, true);437 test.done();438 });439 }440};441exports['controller.envVersions'] = {442 setUp(done) {443 this.sandbox = sinon.sandbox.create();444 this.spinnerStart = this.sandbox.stub(log.spinner, 'start');445 this.spinnerStop = this.sandbox.stub(log.spinner, 'stop');446 this.warn = this.sandbox.stub(log, 'warn');447 this.info = this.sandbox.stub(log, 'info');448 this.basic = this.sandbox.stub(log, 'basic');449 this.error = this.sandbox.stub(log, 'error');450 this.tessel = TesselSimulator({451 name: 'TestTessel'452 });453 this.packageJsonVersion = require('../../package.json').version;454 this.standardTesselCommand = this.sandbox.stub(controller, 'standardTesselCommand').callsFake((options, callback) => {455 return callback(this.tessel);456 });457 this.fetchCurrentBuildInfo = this.sandbox.stub(Tessel.prototype, 'fetchCurrentBuildInfo').callsFake(() => {458 return Promise.resolve('9a85c84f5a03c715908921baaaa9e7397985bc7f');459 });460 this.fetchNodeProcessVersion = this.sandbox.stub(Tessel.prototype, 'fetchNodeProcessVersion').callsFake(() => {461 return Promise.resolve('4.2.1');462 });463 this.requestBuildList = this.sandbox.stub(updates, 'requestBuildList').callsFake(() => {464 return Promise.resolve(465 [{466 'released': '2015-08-20T16:20:08.704Z',467 'sha': '78f2bd20af9eaf76796657186f3010f03a979dc8',468 'version': '0.0.3',469 }, {470 'released': '2015-08-18T15:12:13.070Z',471 'sha': 'bf327359b4a13b4da07bc5776fe8a22ae88d54f9',472 'version': '0.0.2',473 }, {474 'released': '2015-08-12T03:01:57.856Z',475 'sha': '9a85c84f5a03c715908921baaaa9e7397985bc7f',476 'version': '0.0.1',477 }]478 );479 });480 done();481 },482 tearDown(done) {483 this.tessel.mockClose();484 this.sandbox.restore();485 done();486 },487 properVersionsReturned(test) {488 test.expect(8);489 var opts = {};490 controller.envVersions(opts)491 .then(() => {492 // Version command was sent493 test.equal(this.standardTesselCommand.callCount, 1);494 // Get the firmware version495 test.equal(this.fetchCurrentBuildInfo.callCount, 1);496 // Execute `node --version` command on tessel497 test.equal(this.fetchNodeProcessVersion.callCount, 1);498 // Make sure we have some output499 test.equal(this.info.callCount, 4);500 test.equal(this.info.getCall(0).args[0], `Tessel Environment Versions:`);501 // Output of CLI version to console502 test.equal(this.info.getCall(1).args[0], `t2-cli: ${this.packageJsonVersion}`);503 // Output of firmware version to console504 test.equal(this.info.getCall(2).args[0], 't2-firmware: 0.0.1');505 // Output of Node version to console506 test.equal(this.info.getCall(3).args[0], 'Node.js: 4.2.1');507 test.done();508 });509 },510 requestVersionWithoutTessel(test) {511 test.expect(7);512 const message = 'No Tessels Found.';513 this.standardTesselCommand.restore();514 this.standardTesselCommand = this.sandbox.stub(controller, 'standardTesselCommand').callsFake(() => {515 return Promise.reject(message);516 });517 const opts = {};518 controller.envVersions(opts)519 .then(() => {520 // Version command was sent521 test.equal(this.standardTesselCommand.callCount, 1);522 test.equal(this.fetchCurrentBuildInfo.callCount, 0);523 test.equal(this.fetchNodeProcessVersion.callCount, 0);524 // Make sure we have some output525 test.equal(this.info.callCount, 3);526 test.equal(this.info.getCall(0).args[0], `Tessel Environment Versions:`);527 // Output of CLI version to console528 test.equal(this.info.getCall(1).args[0], `t2-cli: ${this.packageJsonVersion}`);529 // Output 'No Tessels Found' message530 test.equal(this.info.getCall(2).args[0], message);531 test.done();532 })533 .catch(() => {534 test.ok(false, 'envVersions was expected to succeed');535 test.done();536 });537 },538 requestVersionsFailure(test) {539 test.expect(1);540 this.fetchCurrentBuildInfo.restore();541 this.fetchCurrentBuildInfo = this.sandbox.stub(this.tessel, 'fetchCurrentBuildInfo').callsFake(() => {542 throw new Error();543 });544 var opts = {};545 controller.envVersions(opts)546 .then(() => {547 test.ok(false, 'envVersions was expected to fail');548 test.done();549 })550 .catch(() => {551 test.ok(true);552 test.done();553 });554 },555 // This happens with development builds.556 noBuildVersionExistsForThisSha(test) {557 test.expect(1);558 const sha = '59ce9c97e275e6e970c1ee668e5591514eb1cd74';559 this.fetchCurrentBuildInfo.restore();560 this.sandbox.stub(this.tessel, 'fetchCurrentBuildInfo').callsFake(() => Promise.resolve(sha));561 var opts = {};562 controller.envVersions(opts)563 .then(() => {564 test.equal(this.info.getCall(2).args[0], `t2-firmware: ${sha}`);565 test.done();566 })567 .catch(() => {568 test.ok(false);569 test.done();570 });571 },572};573exports['Tessel.list'] = {574 setUp(done) {575 var testContext = this;576 this.sandbox = sinon.sandbox.create();577 this.spinnerStart = this.sandbox.stub(log.spinner, 'start');578 this.spinnerStop = this.sandbox.stub(log.spinner, 'stop');579 this.warn = this.sandbox.stub(log, 'warn');580 this.info = this.sandbox.stub(log, 'info');581 this.basic = this.sandbox.stub(log, 'basic');582 this.error = this.sandbox.stub(log, 'error');583 this.processOn = this.sandbox.stub(process, 'on');584 this.activeSeeker = undefined;585 this.seeker = this.sandbox.stub(discover, 'TesselSeeker').callsFake(function() {586 testContext.activeSeeker = this;587 this.start = (opts) => {588 if (opts.timeout && typeof opts.timeout === 'number') {589 setTimeout(this.stop, opts.timeout);590 }591 return this;592 };593 this.stop = () => {594 this.emit('end');595 return this;596 };597 });598 util.inherits(this.seeker, Emitter);599 this.closeTesselConnections = this.sandbox.spy(controller, 'closeTesselConnections');600 this.runHeuristics = this.sandbox.spy(controller, 'runHeuristics');601 this.standardOpts = {602 timeout: 0.01,603 };604 done();605 },606 tearDown(done) {607 this.sandbox.restore();608 done();609 },610 oneUSBTessel(test) {611 test.expect(4);612 var a = newTessel({613 sandbox: this.sandbox,614 authorized: true,615 connectionType: 'USB'616 });617 Tessel.list(this.standardOpts)618 .then(() => {619 test.equal(this.runHeuristics.callCount, 0);620 test.equal(this.closeTesselConnections.callCount, 1);621 test.equal(a.close.callCount, 1);622 test.equal(Array.isArray(this.closeTesselConnections.args[0]), true);623 test.done();624 });625 // We must emit the Tessel sometime after list is called626 // but before the seeker stops searching627 setImmediate(() => {628 this.activeSeeker.emit('tessel', a);629 });630 },631 oneLANTessel(test) {632 test.expect(4);633 var a = newTessel({634 sandbox: this.sandbox,635 authorized: true,636 connectionType: 'LAN'637 });638 Tessel.list(this.standardOpts)639 .then(() => {640 test.equal(this.runHeuristics.callCount, 0);641 test.equal(this.closeTesselConnections.callCount, 1);642 test.equal(a.close.callCount, 1);643 test.equal(Array.isArray(this.closeTesselConnections.args[0]), true);644 test.done();645 });646 // We must emit the Tessel sometime after list is called647 // but before the seeker stops searching648 setImmediate(() => {649 this.activeSeeker.emit('tessel', a);650 });651 },652 explicitlyOnlyReportAuthorizedTessel(test) {653 test.expect(4);654 var a = newTessel({655 sandbox: this.sandbox,656 authorized: false,657 connectionType: 'LAN'658 });659 var customOpts = Object.assign({}, this.standardOpts, {660 authorized: true661 });662 Tessel.list(customOpts)663 .then(() => {664 test.equal(this.runHeuristics.callCount, 0);665 test.equal(this.closeTesselConnections.callCount, 1);666 // "a" will not be closed, because it will never be opened.667 test.equal(a.close.callCount, 0);668 test.equal(Array.isArray(this.closeTesselConnections.args[0]), true);669 test.done();670 }).catch(error => {671 console.log(error);672 });673 this.activeSeeker.emit('tessel', a);674 this.activeSeeker.emit('end');675 },676 explicitlyOnlyReportAuthorizedTesselNoneFound(test) {677 test.expect(1);678 this.standardOpts.authorized = true;679 Tessel.list(this.standardOpts)680 .then(() => {681 test.ok(false, 'This should not be successful');682 test.done();683 }).catch(error => {684 test.equal(error.toString(), 'No Authorized Tessels Found.');685 test.done();686 });687 this.activeSeeker.emit('end');688 },689 oneTesselTwoConnections(test) {690 test.expect(5);691 var usb = newTessel({692 sandbox: this.sandbox,693 connectionType: 'USB',694 name: 'samesies'695 });696 var lan = newTessel({697 sandbox: this.sandbox,698 authorized: true,699 connectionType: 'LAN',700 name: 'samesies'701 });702 Tessel.list(this.standardOpts)703 .then(() => {704 test.equal(this.runHeuristics.callCount, 0);705 test.equal(this.closeTesselConnections.callCount, 1);706 test.equal(usb.close.callCount, 1);707 test.equal(lan.close.callCount, 1);708 test.equal(Array.isArray(this.closeTesselConnections.args[0]), true);709 test.done();710 });711 // We must emit the Tessel sometime after list is called712 // but before the seeker stops searching713 setImmediate(() => {714 this.activeSeeker.emit('tessel', usb);715 this.activeSeeker.emit('tessel', lan);716 });717 },718 multipleDifferentTessels(test) {719 test.expect(5);720 var usb = newTessel({721 sandbox: this.sandbox,722 connectionType: 'USB',723 name: 'foo'724 });725 var lan = newTessel({726 sandbox: this.sandbox,727 authorized: true,728 connectionType: 'LAN',729 name: 'bar'730 });731 Tessel.list(this.standardOpts)732 .then(() => {733 test.equal(this.runHeuristics.callCount, 1);734 test.equal(this.closeTesselConnections.callCount, 1);735 test.equal(Array.isArray(this.closeTesselConnections.args[0]), true);736 test.equal(usb.close.callCount, 1);737 test.equal(lan.close.callCount, 1);738 test.done();739 });740 // We must emit the Tessel sometime after list is called741 // but before the seeker stops searching742 setImmediate(() => {743 this.activeSeeker.emit('tessel', usb);744 this.activeSeeker.emit('tessel', lan);745 });746 },747 runHeuristicsRejection(test) {748 test.expect(1);749 this.runHeuristics.restore();750 this.closeTesselConnections.restore();751 this.runHeuristics = this.sandbox.stub(controller, 'runHeuristics').returns(Promise.reject(new Error('Bogus error')));752 this.closeTesselConnections = this.sandbox.stub(controller, 'closeTesselConnections').returns(Promise.resolve());753 var usb = newTessel({754 sandbox: this.sandbox,755 connectionType: 'USB',756 name: 'foo'757 });758 var lan = newTessel({759 sandbox: this.sandbox,760 authorized: true,761 connectionType: 'LAN',762 name: 'bar'763 });764 Tessel.list(this.standardOpts)765 .catch(error => {766 test.equal(error.toString(), 'Error: Bogus error');767 }).then(() => {768 usb.mockClose();769 lan.mockClose();770 test.done();771 });772 // Make sure the multiple tessel path is taken773 this.activeSeeker.emit('tessel', usb);774 this.activeSeeker.emit('tessel', lan);775 this.activeSeeker.emit('end');776 },777};778exports['Tessel.get'] = {779 setUp(done) {780 var testContext = this;781 this.sandbox = sinon.sandbox.create();782 this.spinnerStart = this.sandbox.stub(log.spinner, 'start');783 this.spinnerStop = this.sandbox.stub(log.spinner, 'stop');784 this.warn = this.sandbox.stub(log, 'warn');785 this.info = this.sandbox.stub(log, 'info');786 this.basic = this.sandbox.stub(log, 'basic');787 this.error = this.sandbox.stub(log, 'error');788 this.processOn = this.sandbox.stub(process, 'on');789 this.activeSeeker = undefined;790 this.seeker = this.sandbox.stub(discover, 'TesselSeeker').callsFake(function Seeker() {791 this.start = (opts) => {792 testContext.activeSeeker = this;793 testContext.sandbox.spy(this, 'removeAllListeners');794 this.msg = {795 noAuth: 'No Authorized Tessels Found.',796 auth: 'No Tessels Found.'797 };798 if (opts.timeout && typeof opts.timeout === 'number') {799 setTimeout(this.stop, opts.timeout);800 }801 return this;802 };803 this.stop = () => {804 testContext.activeSeeker.emit('end');805 return this;806 };807 });808 util.inherits(this.seeker, Emitter);809 this.closeTesselConnections = this.sandbox.stub(controller, 'closeTesselConnections');810 this.reconcileTessels = this.sandbox.spy(controller, 'reconcileTessels');811 this.runHeuristics = this.sandbox.spy(controller, 'runHeuristics');812 this.standardOpts = {813 timeout: 0.01,814 };815 done();816 },817 tearDown(done) {818 this.sandbox.restore();819 done();820 },821 fallbackTimeout(test) {822 test.expect(7);823 controller.closeTesselConnections.returns(Promise.resolve());824 var a = newTessel({825 sandbox: this.sandbox,826 authorized: true,827 connectionType: 'LAN',828 name: 'the_name'829 });830 var customOpts = {831 key: this.standardOpts.key,832 name: 'the_name',833 timeout: 0,834 };835 Tessel.get(customOpts)836 .then(() => {837 test.equal(this.activeSeeker.removeAllListeners.callCount, 1);838 test.equal(this.reconcileTessels.callCount, 0);839 test.equal(this.runHeuristics.callCount, 0);840 test.equal(this.closeTesselConnections.callCount, 1);841 test.equal(Array.isArray(this.closeTesselConnections.args[0]), true);842 test.equal(this.info.callCount, 2);843 test.equal(this.info.lastCall.args[0].includes('the_name'), true);844 test.done();845 });846 // We must emit the Tessel sometime after list is called847 // but before the seeker stops searching848 setImmediate(() => {849 this.activeSeeker.emit('tessel', a);850 });851 },852 oneNamedTessel(test) {853 test.expect(7);854 controller.closeTesselConnections.returns(Promise.resolve());855 var a = newTessel({856 sandbox: this.sandbox,857 authorized: true,858 connectionType: 'LAN',859 name: 'the_name'860 });861 var customOpts = {862 timeout: this.standardOpts.timeout,863 key: this.standardOpts.key,864 name: 'the_name'865 };866 Tessel.get(customOpts)867 .then(() => {868 test.equal(this.activeSeeker.removeAllListeners.callCount, 1);869 test.equal(this.reconcileTessels.callCount, 0);870 test.equal(this.runHeuristics.callCount, 0);871 test.equal(this.closeTesselConnections.callCount, 1);872 test.equal(Array.isArray(this.closeTesselConnections.args[0]), true);873 test.equal(this.info.callCount, 2);874 test.equal(this.info.lastCall.args[0].includes('the_name'), true);875 test.done();876 });877 // We must emit the Tessel sometime after list is called878 // but before the seeker stops searching879 setImmediate(() => {880 this.activeSeeker.emit('tessel', a);881 });882 },883 oneUnNamedTessel(test) {884 test.expect(7);885 controller.closeTesselConnections.returns(Promise.resolve());886 var a = newTessel({887 sandbox: this.sandbox,888 authorized: true,889 connectionType: 'LAN',890 name: 'the_name'891 });892 Tessel.get(this.standardOpts)893 .then(() => {894 test.equal(this.activeSeeker.removeAllListeners.callCount, 0);895 test.equal(this.reconcileTessels.callCount, 0);896 test.equal(this.runHeuristics.callCount, 0);897 test.equal(this.closeTesselConnections.callCount, 1);898 test.equal(Array.isArray(this.closeTesselConnections.args[0]), true);899 test.equal(this.info.callCount, 2);900 test.equal(this.info.lastCall.args[0].includes('the_name'), true);901 test.done();902 });903 // We must emit the Tessel sometime after list is called904 // but before the seeker stops searching905 setImmediate(() => {906 this.activeSeeker.emit('tessel', a);907 });908 },909 logAndFinishSpecificTessel(test) {910 test.expect(2);911 controller.closeTesselConnections.returns(Promise.resolve());912 this.menuPrompt = this.sandbox.stub(Menu, 'prompt').callsFake((prompt) => {913 var value = prompt.translate('\tUSB\ta\t');914 return Promise.resolve(value);915 });916 var a = newTessel({917 sandbox: this.sandbox,918 authorized: true,919 connectionType: 'LAN',920 name: 'a'921 });922 var b = newTessel({923 sandbox: this.sandbox,924 authorized: true,925 connectionType: 'LAN',926 name: 'b'927 });928 var customOpts = Object.assign({}, this.standardOpts, {929 name: 'a'930 });931 Tessel.get(customOpts)932 .then(() => {933 a.mockClose();934 b.mockClose();935 test.equal(this.activeSeeker.removeAllListeners.callCount, 1);936 test.equal(this.info.callCount, 2);937 test.done();938 });939 // We must emit the Tessel sometime after list is called940 // but before the seeker stops searching941 this.activeSeeker.emit('tessel', a);942 this.activeSeeker.emit('tessel', b);943 this.activeSeeker.emit('end');944 },945 oneUnamedTesselTwoConnections(test) {946 test.expect(7);947 controller.closeTesselConnections.returns(Promise.resolve());948 var usb = newTessel({949 sandbox: this.sandbox,950 connectionType: 'USB',951 name: 'samesies'952 });953 var lan = newTessel({954 sandbox: this.sandbox,955 authorized: true,956 connectionType: 'LAN',957 name: 'samesies'958 });959 var customOpts = this.standardOpts;960 customOpts.lanPrefer = true;961 Tessel.get(customOpts)962 .then(() => {963 test.equal(this.activeSeeker.removeAllListeners.callCount, 0);964 test.equal(this.reconcileTessels.callCount, 1);965 test.equal(this.runHeuristics.callCount, 1);966 test.equal(this.closeTesselConnections.callCount, 1);967 test.equal(Array.isArray(this.closeTesselConnections.args[0]), true);968 test.equal(this.info.callCount, 2);969 test.equal(this.info.lastCall.args[0].includes('samesies'), true);970 test.done();971 });972 // We must emit the Tessel sometime after list is called973 // but before the seeker stops searching974 setImmediate(() => {975 this.activeSeeker.emit('tessel', usb);976 this.activeSeeker.emit('tessel', lan);977 });978 },979 twoDifferentTesselsPickOne(test) {980 test.expect(6);981 controller.closeTesselConnections.returns(Promise.resolve());982 this.runHeuristics.restore();983 this.runHeuristics = this.sandbox.stub(controller, 'runHeuristics').callsFake(() => {984 return Promise.reject(new controller.HeuristicAmbiguityError('Bogus error'));985 });986 this.menuPrompt = this.sandbox.stub(Menu, 'prompt').callsFake((prompt) => {987 var value = prompt.translate('\tUSB\ta\t');988 return Promise.resolve(value);989 });990 var usb = newTessel({991 sandbox: this.sandbox,992 connectionType: 'USB',993 name: 'a'994 });995 var lan = newTessel({996 sandbox: this.sandbox,997 authorized: true,998 connectionType: 'LAN',999 name: 'a'1000 });1001 var customOpts = this.standardOpts;1002 Tessel.get(customOpts)1003 .catch(() => {1004 test.equal(this.activeSeeker.removeAllListeners.callCount, 0);1005 test.equal(this.reconcileTessels.callCount, 1);1006 test.equal(this.runHeuristics.callCount, 1);1007 test.equal(this.closeTesselConnections.callCount, 1);1008 test.equal(Array.isArray(this.closeTesselConnections.args[0]), true);1009 test.equal(this.info.callCount, 1);1010 test.done();1011 });1012 this.activeSeeker.emit('tessel', usb);1013 this.activeSeeker.emit('tessel', lan);1014 this.activeSeeker.emit('end');1015 },1016 standardCommandNoTessels(test) {1017 test.expect(3);1018 controller.standardTesselCommand(this.standardOpts, function() {1019 // Doesn't matter what this function does b/c Tessel.get will fail1020 return Promise.resolve();1021 })1022 .catch(error => {1023 test.equal(controller.tessel, null);1024 // We don't need to close any connections because none were found1025 test.equal(this.closeTesselConnections.callCount, 0);1026 test.equal(typeof error, 'string');1027 test.done();1028 });1029 },1030 standardCommandSuccess(test) {1031 test.expect(5);1032 controller.closeTesselConnections.returns(Promise.resolve());1033 var optionalValue = 'testValue';1034 controller.standardTesselCommand(this.standardOpts, tessel => {1035 // Make sure we have been given the tessel that was emitted1036 test.deepEqual(tessel, usb);1037 // The active tessel is available at controller.tessel1038 test.equal(controller.tessel, usb);1039 // Finish the command1040 return Promise.resolve(optionalValue);1041 })1042 .then(returnedValue => {1043 // We need to close the connection of the Tessel we found1044 // We close once at the end of Tessel.get and again after the standard command1045 test.equal(this.closeTesselConnections.callCount, 2);1046 // Make sure we closed the connection of the exact Tessel we emitted1047 test.equal(this.closeTesselConnections.args[1][0][0], usb);1048 // Ensure we got the optional returned value1049 test.equal(optionalValue, returnedValue);1050 test.done();1051 })1052 .catch(error => {1053 test.ok(false, error.toString());1054 test.done();1055 });1056 var usb = newTessel({1057 sandbox: this.sandbox,1058 connectionType: 'USB',1059 name: 'USBTessel'1060 });1061 // We must emit the Tessel sometime after list is called1062 // but before the seeker stops searching1063 setImmediate(() => {1064 this.activeSeeker.emit('tessel', usb);1065 });1066 },1067 standardCommandFailed(test) {1068 test.expect(4);1069 controller.closeTesselConnections.returns(Promise.resolve());1070 var errMessage = 'This command failed';1071 controller.standardTesselCommand(this.standardOpts, function(tessel) {1072 // Make sure we have been given the tessel that was emitted1073 test.deepEqual(tessel, usb);1074 // Finish the command1075 return Promise.reject(errMessage);1076 })1077 .then(() => {1078 test.ok(false, 'standardTesselCommand was expected to fail, but did not.');1079 test.done();1080 })1081 .catch(error => {1082 // Make sure the error messages are passed through properly1083 test.equal(errMessage, error);1084 // We need to close the connection of the Tessel we found1085 // We close once at the end of Tessel.get and again after the standard command1086 test.equal(this.closeTesselConnections.callCount, 2);1087 // Make sure we closed the connection of the exact Tessel we emitted1088 test.equal(this.closeTesselConnections.args[1][0][0], usb);1089 test.done();1090 });1091 var usb = newTessel({1092 sandbox: this.sandbox,1093 connectionType: 'USB',1094 name: 'USBTessel'1095 });1096 // We must emit the Tessel sometime after list is called1097 // but before the seeker stops searching1098 setImmediate(() => {1099 this.activeSeeker.emit('tessel', usb);1100 });1101 },1102 standardCommandSigInt(test) {1103 test.expect(2);1104 controller.closeTesselConnections.returns(Promise.resolve());1105 controller.standardTesselCommand(this.standardOpts, function() {1106 // This command doesn't do anything. It won't resolve so if we do get1107 // to the next clause, it's due to the sigint1108 })1109 .then(() => {1110 // We need to close the connection of the Tessel we found1111 // We close once at the end of Tessel.get and again after the standard command1112 test.equal(this.closeTesselConnections.callCount, 2);1113 // Make sure we closed the connection of the exact Tessel we emitted1114 test.equal(this.closeTesselConnections.args[1][0][0], usb);1115 test.done();1116 })1117 .catch(error => {1118 test.ok(false, error.toString());1119 test.done();1120 });1121 var usb = newTessel({1122 sandbox: this.sandbox,1123 connectionType: 'USB',1124 name: 'USBTessel'1125 });1126 // We must emit the Tessel sometime after list is called1127 // but before the seeker stops searching1128 setImmediate(() => {1129 this.activeSeeker.emit('tessel', usb);1130 process.emit('SIGINT');1131 });1132 },1133};1134exports['controller.createAccessPoint'] = {1135 setUp(done) {1136 this.sandbox = sinon.sandbox.create();1137 this.spinnerStart = this.sandbox.stub(log.spinner, 'start');1138 this.spinnerStop = this.sandbox.stub(log.spinner, 'stop');1139 this.warn = this.sandbox.stub(log, 'warn');1140 this.info = this.sandbox.stub(log, 'info');1141 this.basic = this.sandbox.stub(log, 'basic');1142 this.error = this.sandbox.stub(log, 'error');1143 // stub this command to avoid authoized Tessel validation1144 this.standardTesselCommand = this.sandbox.stub(controller, 'standardTesselCommand').returns(Promise.resolve(true));1145 done();1146 },1147 tearDown(done) {1148 this.sandbox.restore();1149 done();1150 },1151 noNetworkSSID(test) {1152 test.expect(1);1153 controller.connectToNetwork({1154 ssid: undefined1155 })1156 .catch(error => {1157 test.ok(error);1158 test.done();1159 });1160 },1161 noNetworkPasswordWithSecurity(test) {1162 test.expect(1);1163 controller.connectToNetwork({1164 ssid: 'test',1165 password: undefined,1166 security: 'psk2'1167 })1168 .catch(error => {1169 test.ok(error);1170 test.done();1171 });1172 },1173 invalidNetworkSecurityOption(test) {1174 test.expect(1);1175 controller.connectToNetwork({1176 ssid: 'test',1177 password: undefined,1178 security: 'reallySecure'1179 })1180 .catch(error => {1181 test.ok(error);1182 test.done();1183 });1184 },1185 noAccessPointSSID(test) {1186 test.expect(1);1187 controller.createAccessPoint({1188 ssid: undefined1189 })1190 .catch(error => {1191 test.ok(error);1192 test.done();1193 });1194 },1195 noAccessPointPasswordWithSecurity(test) {1196 test.expect(1);1197 controller.createAccessPoint({1198 ssid: 'test',1199 password: undefined,1200 security: 'psk2'1201 })1202 .catch(error => {1203 test.ok(error);1204 test.done();1205 });1206 },1207 invalidAccessPointSecurityOption(test) {1208 test.expect(1);1209 controller.createAccessPoint({1210 ssid: 'test',1211 password: undefined,1212 security: 'reallySecure'1213 })1214 .catch(error => {1215 test.ok(true, error.toString());1216 test.done();1217 });1218 },1219 invalidAccessPointWEPPasswordCharacters(test) {1220 test.expect(1);1221 controller.createAccessPoint({1222 ssid: 'test',1223 password: 'nothexdigits',1224 security: 'wep'1225 })1226 .catch(error => {1227 test.ok(error);1228 test.done();1229 });1230 },1231 invalidAccessPointWEPPasswordLength(test) {1232 test.expect(1);1233 controller.createAccessPoint({1234 ssid: 'test',1235 password: '0123456789ABCDEF',1236 security: 'wep'1237 })1238 .catch(error => {1239 test.ok(error);1240 test.done();1241 });1242 },1243 validAccessPointWEPPassword(test) {1244 test.expect(1);1245 controller.createAccessPoint({1246 ssid: 'test',1247 password: '01234ABCDE',1248 security: 'wep'1249 })1250 .then((settings) => {1251 test.ok(settings);1252 test.done();1253 })1254 .catch(error => {1255 test.fail(error.toString());1256 test.done();1257 });1258 },1259 invalidAccessPointPSKPasswordCharacters(test) {1260 test.expect(1);1261 controller.createAccessPoint({1262 ssid: 'test',1263 password: 'Password™',1264 security: 'psk'1265 })1266 .catch(error => {1267 test.ok(error);1268 test.done();1269 });1270 },1271 invalidAccessPointPSKASCIIPasswordTooShort(test) {1272 test.expect(1);1273 controller.createAccessPoint({1274 ssid: 'test',1275 password: 'short',1276 security: 'psk'1277 })1278 .catch(error => {1279 test.ok(error);1280 test.done();1281 });1282 },1283 invalidAccessPointPSKASCIIPasswordTooLong(test) {1284 test.expect(1);1285 controller.createAccessPoint({1286 ssid: 'test',1287 password: 'this is a very long passphrase. in fact, it is over 63 characters, which makes it invalid.',1288 security: 'psk'1289 })1290 .catch(error => {1291 test.ok(error);1292 test.done();1293 });1294 },1295 invalidAccessPointPSKHexPasswordTooShort(test) {1296 test.expect(1);1297 controller.createAccessPoint({1298 ssid: 'test',1299 password: 'DEAD',1300 security: 'psk'1301 })1302 .catch(error => {1303 test.ok(error);1304 test.done();1305 });1306 },1307 invalidAccessPointPSKHexPasswordTooLong(test) {1308 test.expect(1);1309 controller.createAccessPoint({1310 ssid: 'test',1311 password: 'DEADDEADDEADDEADDEADDEADDEADDEADDEADDEADDEADDEADDEADDEADDEADDEADDEAD',1312 security: 'psk'1313 })1314 .catch(error => {1315 test.ok(error);1316 test.done();1317 });1318 },1319 validAccessPointPSKPassword(test) {1320 test.expect(1);1321 controller.createAccessPoint({1322 ssid: 'test',1323 password: 'ValidPassword!',1324 security: 'psk'1325 })1326 .then((settings) => {1327 test.ok(settings);1328 test.done();1329 })1330 .catch((error) => {1331 test.fail(error.toString());1332 test.done();1333 });1334 },1335};1336exports['controller.getWifiInfo'] = {1337 setUp(done) {1338 this.sandbox = sinon.sandbox.create();1339 this.spinnerStart = this.sandbox.stub(log.spinner, 'start');1340 this.spinnerStop = this.sandbox.stub(log.spinner, 'stop');1341 this.warn = this.sandbox.stub(log, 'warn');1342 this.info = this.sandbox.stub(log, 'info');1343 this.basic = this.sandbox.stub(log, 'basic');1344 this.error = this.sandbox.stub(log, 'error');1345 // stub this command to avoid authoized Tessel validation1346 this.standardTesselCommand = this.sandbox.stub(controller, 'standardTesselCommand').returns(Promise.resolve(true));1347 this.lanbot = newTessel({1348 sandbox: this.sandbox,1349 authorized: true,1350 connectionType: 'LAN',1351 name: 'lanbot'1352 });1353 done();1354 },1355 tearDown(done) {1356 this.sandbox.restore();1357 done();1358 },1359 requestNetworkInfo(test) {1360 test.expect(5);1361 const options = {};1362 controller.standardTesselCommand.restore();1363 this.sandbox.stub(controller, 'standardTesselCommand').callsFake(1364 (options, callback) => callback(this.lanbot)1365 );1366 this.sandbox.stub(this.lanbot, 'getWifiInfo').returns(1367 Promise.resolve(global.networkInfo)1368 );1369 controller.getWifiInfo(options)1370 .then(() => {1371 test.equal(this.info.callCount, 4);1372 test.equal(this.info.getCall(0).args[0], 'SSID: skynet');1373 test.equal(this.info.getCall(1).args[0], 'IP Address: 000.000.000.000');1374 test.equal(this.info.getCall(2).args[0], 'Signal Strength: (70/70)');1375 test.equal(this.info.getCall(3).args[0], 'Bitrate: 22 Mbps');1376 test.done();1377 });1378 },1379};1380exports['controller.root'] = {1381 setUp(done) {1382 this.sandbox = sinon.sandbox.create();1383 this.spinnerStart = this.sandbox.stub(log.spinner, 'start');1384 this.spinnerStop = this.sandbox.stub(log.spinner, 'stop');1385 this.warn = this.sandbox.stub(log, 'warn');1386 this.info = this.sandbox.stub(log, 'info');1387 this.basic = this.sandbox.stub(log, 'basic');1388 this.error = this.sandbox.stub(log, 'error');1389 this.standardTesselCommand = this.sandbox.stub(controller, 'standardTesselCommand').returns(Promise.resolve());1390 function FakeChild() {}1391 FakeChild.prototype = Object.create(Emitter.prototype);1392 this.child = new FakeChild();1393 this.spawn = this.sandbox.stub(cp, 'spawn').callsFake(() => this.child);1394 done();1395 },1396 tearDown(done) {1397 this.sandbox.restore();1398 done();1399 },1400 setsOptsLanTrue(test) {1401 test.expect(3);1402 var opts = {};1403 controller.root(opts)1404 .then(() => {1405 var options = this.standardTesselCommand.lastCall.args[0];1406 test.equal(this.standardTesselCommand.callCount, 1);1407 test.equal(options, opts);1408 test.equal(options.lan, true);1409 test.done();1410 });1411 },1412 setsOptsUsbFalseAndWarns(test) {1413 test.expect(4);1414 var opts = {1415 usb: true1416 };1417 this.warn.restore();1418 this.warn = this.sandbox.stub(log, 'warn');1419 controller.root(opts)1420 .then(() => {1421 var options = this.standardTesselCommand.lastCall.args[0];1422 test.equal(this.standardTesselCommand.callCount, 1);1423 test.equal(options, opts);1424 test.equal(options.usb, false);1425 test.equal(this.warn.callCount, 2);1426 test.done();1427 });1428 },1429 setsAuthorizedTrue(test) {1430 test.expect(3);1431 var opts = {};1432 controller.root(opts)1433 .then(() => {1434 var options = this.standardTesselCommand.lastCall.args[0];1435 test.equal(this.standardTesselCommand.callCount, 1);1436 test.equal(options, opts);1437 test.equal(options.authorized, true);1438 test.done();1439 });1440 },1441 openShell(test) {1442 test.expect(6);1443 var sandbox = this.sandbox;1444 var tessel = newTessel({1445 authorized: true,1446 sandbox: sandbox,1447 connectionType: 'LAN',1448 });1449 var testIP = '192.1.1.1';1450 tessel.lanConnection.ip = testIP;1451 var testKey = '~/fake';1452 this.standardTesselCommand.restore();1453 this.standardTesselCommand = this.sandbox.stub(controller, 'standardTesselCommand').callsFake((options, callback) => {1454 return callback(tessel);1455 });1456 // Return our own local auth key (it won't be set because we have stubbed1457 // that functionality out of standardTesselCommand)1458 // this.sandbox.stub(Tessel, 'LOCAL_AUTH_KEY').callsFake(testKey);1459 var opd = Object.getOwnPropertyDescriptor(Tessel, 'LOCAL_AUTH_KEY');1460 Object.defineProperty(Tessel, 'LOCAL_AUTH_KEY', {1461 get() {1462 return testKey;1463 }1464 });1465 controller.root({1466 key: testKey1467 })1468 .then(() => {1469 // Only spawn one process1470 test.ok(this.spawn.calledOnce);1471 // That process is ssh1472 test.equal(this.spawn.firstCall.args[0], 'ssh');1473 // We want to make sure we provide a key path1474 test.equal(this.spawn.firstCall.args[1][0], '-i');1475 // Make sure it's the optional key we provided1476 test.equal(this.spawn.firstCall.args[1][1], testKey);1477 // Make sure it's using the correct IP address1478 test.equal(this.spawn.firstCall.args[1][2], 'root@' + testIP);1479 // We want to ensure stdio streams are piped to the console1480 test.equal(this.spawn.firstCall.args[2].stdio, 'inherit');1481 Object.defineProperty(Tessel, 'LOCAL_AUTH_KEY', opd);1482 test.done();1483 });1484 setImmediate(() => {1485 this.child.emit('close');1486 });1487 },1488 shellOpenError(test) {1489 test.expect(1);1490 var sandbox = this.sandbox;1491 var tessel = newTessel({1492 authorized: true,1493 sandbox: sandbox,1494 connectionType: 'LAN',1495 });1496 this.standardTesselCommand.restore();1497 this.standardTesselCommand = this.sandbox.stub(controller, 'standardTesselCommand').callsFake((options, callback) => {1498 return callback(tessel);1499 });1500 var errMessage = 'Your child is a fake!';1501 controller.root({})1502 .then(() => {1503 // Only spawn one process1504 test.ok(false, 'Should have rejected the root promise.');1505 test.done();1506 })1507 .catch(error => {1508 test.ok(error.includes(errMessage));1509 test.done();1510 });1511 setImmediate(() => {1512 this.child.emit('error', new Error(errMessage));1513 });1514 }1515};1516exports['controller.printAvailableNetworks'] = {1517 setUp(done) {1518 this.sandbox = sinon.sandbox.create();1519 this.spinnerStart = this.sandbox.stub(log.spinner, 'start');1520 this.spinnerStop = this.sandbox.stub(log.spinner, 'stop');1521 this.warn = this.sandbox.stub(log, 'warn');1522 this.info = this.sandbox.stub(log, 'info');1523 this.basic = this.sandbox.stub(log, 'basic');1524 this.error = this.sandbox.stub(log, 'error');1525 this.tessel = TesselSimulator();1526 this.standardTesselCommand = this.sandbox.stub(controller, 'standardTesselCommand').callsFake((options, callback) => {1527 callback(this.tessel);1528 return Promise.resolve(this.tessel);1529 });1530 this.tessel.name = 'robocop';1531 colors.enabled = false;1532 done();1533 },1534 tearDown(done) {1535 this.tessel.mockClose();1536 this.sandbox.restore();1537 colors.enabled = true;1538 done();1539 },1540 listCountOfVisibleToTesselSingle(test) {1541 test.expect(5);1542 this.findAvailableNetworks = this.sandbox.stub(this.tessel, 'findAvailableNetworks').callsFake(() => {1543 return Promise.resolve([{1544 ssid: 'foo',1545 quality: '100/100'1546 }]);1547 });1548 controller.printAvailableNetworks({})1549 .then(() => {1550 test.equal(this.info.callCount, 2);1551 test.equal(this.basic.callCount, 1);1552 test.equal(this.info.firstCall.args[0], 'Scanning for visible networks...');1553 test.equal(this.info.lastCall.args[0], 'Found 1 network visible to robocop:');1554 test.equal(this.basic.lastCall.args[0], '\tfoo (100/100)');1555 test.done();1556 })1557 .catch(error => {1558 test.ok(false, error.toString());1559 test.done();1560 });1561 },1562 listCountOfVisibleToTesselPlural(test) {1563 test.expect(6);1564 this.findAvailableNetworks = this.sandbox.stub(this.tessel, 'findAvailableNetworks').callsFake(() => {1565 return Promise.resolve([{1566 ssid: 'foo',1567 quality: '100/100'1568 }, {1569 ssid: 'bar',1570 quality: '100/100'1571 }]);1572 });1573 controller.printAvailableNetworks({})1574 .then(() => {1575 test.equal(this.info.callCount, 2);1576 test.equal(this.basic.callCount, 2);1577 test.equal(this.info.firstCall.args[0], 'Scanning for visible networks...');1578 test.equal(this.info.lastCall.args[0], 'Found 2 networks visible to robocop:');1579 test.equal(this.basic.firstCall.args[0], '\tfoo (100/100)');1580 test.equal(this.basic.lastCall.args[0], '\tbar (100/100)');1581 test.done();1582 })1583 .catch(error => {1584 test.ok(false, error.toString());1585 test.done();1586 });1587 },1588 listCountOfVisibleToTesselPluralZero(test) {1589 test.expect(4);1590 this.findAvailableNetworks = this.sandbox.stub(this.tessel, 'findAvailableNetworks').callsFake(() => {1591 return Promise.resolve([]);1592 });1593 controller.printAvailableNetworks({})1594 .then(() => {1595 test.equal(this.info.callCount, 2);1596 test.equal(this.basic.callCount, 0);1597 test.equal(this.info.firstCall.args[0], 'Scanning for visible networks...');1598 test.equal(this.info.lastCall.args[0], 'Found 0 networks visible to robocop:');1599 test.done();1600 })1601 .catch(error => {1602 test.ok(false, error.toString());1603 test.done();1604 });1605 },1606};1607exports['controller.uninstaller'] = {1608 setUp(done) {1609 this.sandbox = sinon.sandbox.create();1610 this.spinnerStart = this.sandbox.stub(log.spinner, 'start');1611 this.spinnerStop = this.sandbox.stub(log.spinner, 'stop');1612 this.warn = this.sandbox.stub(log, 'warn');1613 this.info = this.sandbox.stub(log, 'info');1614 this.basic = this.sandbox.stub(log, 'basic');1615 this.error = this.sandbox.stub(log, 'error');1616 this.homedir = this.sandbox.stub(installer, 'homedir').returns(Promise.resolve());1617 done();1618 },1619 tearDown(done) {1620 this.sandbox.restore();1621 done();1622 },1623 optionsOperationCallThrough(test) {1624 test.expect(1);1625 controller.uninstaller({1626 operation: 'homedir'1627 })1628 .then(() => {1629 test.equal(this.homedir.callCount, 1);1630 test.done();1631 });1632 },1633};1634exports['controller.reboot'] = {1635 setUp(done) {1636 this.sandbox = sinon.sandbox.create();1637 this.spinnerStart = this.sandbox.stub(log.spinner, 'start');1638 this.spinnerStop = this.sandbox.stub(log.spinner, 'stop');1639 this.warn = this.sandbox.stub(log, 'warn');1640 this.info = this.sandbox.stub(log, 'info');1641 this.basic = this.sandbox.stub(log, 'basic');1642 this.error = this.sandbox.stub(log, 'error');1643 this.tessel = TesselSimulator({1644 name: 'TestTessel'1645 });1646 this.reboot = this.sandbox.stub(this.tessel, 'reboot');1647 this.standardTesselCommand = this.sandbox.stub(controller, 'standardTesselCommand').callsFake((options, callback) => {1648 return callback(this.tessel);1649 });1650 done();1651 },1652 tearDown(done) {1653 this.tessel.mockClose();1654 this.sandbox.restore();1655 done();1656 },1657 success(test) {1658 test.expect(2);1659 this.reboot.returns(Promise.resolve());1660 controller.reboot({})1661 .then(() => {1662 test.equal(this.reboot.callCount, 1);1663 test.equal(this.info.callCount, 1);1664 test.done();1665 });1666 },1667 failure(test) {1668 test.expect(1);1669 this.reboot.returns(Promise.reject());1670 controller.reboot({})1671 .catch(() => {1672 test.equal(this.reboot.callCount, 1);1673 test.done();1674 });1675 },1676};1677exports['controller.updateWithRemoteBuilds'] = {1678 setUp(done) {1679 this.sandbox = sinon.sandbox.create();1680 this.spinnerStart = this.sandbox.stub(log.spinner, 'start');1681 this.spinnerStop = this.sandbox.stub(log.spinner, 'stop');1682 this.warn = this.sandbox.stub(log, 'warn');1683 this.info = this.sandbox.stub(log, 'info');1684 this.basic = this.sandbox.stub(log, 'basic');1685 this.error = this.sandbox.stub(log, 'error');1686 this.tessel = newTessel({1687 sandbox: this.sandbox,1688 authorized: true,1689 connectionType: 'LAN'1690 });1691 this.requestBuildList = this.sandbox.stub(updates, 'requestBuildList').callsFake(() => {1692 return Promise.resolve(1693 [{1694 'released': '2015-08-20T16:20:08.704Z',1695 'sha': '78f2bd20af9eaf76796657186f3010f03a979dc8',1696 'version': '0.0.3',1697 }, {1698 'released': '2015-08-18T15:12:13.070Z',1699 'sha': 'bf327359b4a13b4da07bc5776fe8a22ae88d54f9',1700 'version': '0.0.2',1701 }, {1702 'released': '2015-08-12T03:01:57.856Z',1703 'sha': '9a85c84f5a03c715908921baaaa9e7397985bc7f',1704 'version': '0.0.1',1705 }]1706 );1707 });1708 colors.enabled = false;1709 done();1710 },1711 tearDown(done) {1712 this.tessel.mockClose();1713 this.sandbox.restore();1714 colors.enabled = true;1715 done();1716 },1717 noUsbRejection(test) {1718 test.expect(1);1719 controller.updateWithRemoteBuilds({}, this.tessel)1720 .catch(error => {1721 test.equal(error.toString(), 'Must have Tessel connected over USB to complete update. Aborting update.');1722 test.done();1723 });1724 },1725 noForceRejection(test) {1726 test.expect(3);1727 this.tessel = TesselSimulator({1728 name: 'TestTessel'1729 });1730 this.fetchCurrentBuildInfo = this.sandbox.stub(this.tessel, 'fetchCurrentBuildInfo').returns(Promise.reject(new Error('No such file or directory')));1731 controller.updateWithRemoteBuilds({1732 force: false1733 }, this.tessel)1734 .catch(error => {1735 test.equal(error.toString(), 'Error: No such file or directory');1736 test.equal(this.warn.callCount, 1);1737 test.equal(this.warn.lastCall.args[0].includes('Could not find firmware version on '), true);1738 test.done();1739 });1740 },1741};1742exports['controller.restore'] = {1743 setUp(done) {1744 this.sandbox = sinon.sandbox.create();1745 this.spinnerStart = this.sandbox.stub(log.spinner, 'start');1746 this.spinnerStop = this.sandbox.stub(log.spinner, 'stop');1747 this.warn = this.sandbox.stub(log, 'warn');1748 this.info = this.sandbox.stub(log, 'info');1749 this.basic = this.sandbox.stub(log, 'basic');1750 this.error = this.sandbox.stub(log, 'error');1751 this.tessel = TesselSimulator({1752 name: 'TestTessel'1753 });1754 this.get = this.sandbox.stub(controller, 'get').returns(Promise.resolve(this.tessel));1755 this.tesselRestore = this.sandbox.stub(this.tessel, 'restore').returns(Promise.resolve());1756 done();1757 },1758 tearDown(done) {1759 this.tessel.mockClose();1760 this.sandbox.restore();1761 done();1762 },1763 restoreCallPipelineResolved(test) {1764 test.expect(2);1765 controller.restore({})1766 .then(() => {1767 test.equal(this.get.callCount, 1);1768 test.equal(this.tesselRestore.callCount, 1);1769 test.done();1770 });1771 },1772 restoreCallPipelineRejected(test) {1773 test.expect(2);1774 this.tesselRestore.restore();1775 this.tesselRestore = this.sandbox.stub(this.tessel, 'restore').returns(Promise.reject(new Error('whatever')));1776 controller.restore({})1777 .catch(() => {1778 test.equal(this.get.callCount, 1);1779 test.equal(this.tesselRestore.callCount, 1);1780 test.done();1781 });1782 },1783};1784exports['controller.deploy'] = {1785 setUp(done) {1786 this.sandbox = sinon.sandbox.create();1787 this.spinnerStart = this.sandbox.stub(log.spinner, 'start');1788 this.spinnerStop = this.sandbox.stub(log.spinner, 'stop');1789 this.warn = this.sandbox.stub(log, 'warn');1790 this.info = this.sandbox.stub(log, 'info');1791 this.basic = this.sandbox.stub(log, 'basic');1792 this.error = this.sandbox.stub(log, 'error');1793 this.tessel = TesselSimulator({1794 name: 'TestTessel'1795 });1796 this.deploy = this.sandbox.stub(this.tessel, 'deploy').returns(Promise.resolve());1797 this.standardTesselCommand = this.sandbox.stub(controller, 'standardTesselCommand').callsFake((options, callback) => {1798 return callback(this.tessel);1799 });1800 done();1801 },1802 tearDown(done) {1803 this.tessel.mockClose();1804 this.sandbox.restore();1805 done();1806 },1807 deployCallPipeline(test) {1808 test.expect(2);1809 var options = {};1810 controller.deploy(options)1811 .then(() => {1812 test.equal(this.standardTesselCommand.lastCall.args[0], options);1813 test.equal(this.deploy.callCount, 1);1814 test.done();1815 });1816 },1817};1818exports['controller.restart'] = {1819 setUp(done) {1820 this.sandbox = sinon.sandbox.create();1821 this.spinnerStart = this.sandbox.stub(log.spinner, 'start');1822 this.spinnerStop = this.sandbox.stub(log.spinner, 'stop');1823 this.warn = this.sandbox.stub(log, 'warn');1824 this.info = this.sandbox.stub(log, 'info');1825 this.basic = this.sandbox.stub(log, 'basic');1826 this.error = this.sandbox.stub(log, 'error');1827 this.tessel = TesselSimulator({1828 name: 'TestTessel'1829 });1830 this.restart = this.sandbox.stub(this.tessel, 'restart').returns(Promise.resolve());1831 this.standardTesselCommand = this.sandbox.stub(controller, 'standardTesselCommand').callsFake((options, callback) => {1832 return callback(this.tessel);1833 });1834 done();1835 },1836 tearDown(done) {1837 this.tessel.mockClose();1838 this.sandbox.restore();1839 done();1840 },1841 restartCallPipeline(test) {1842 test.expect(2);1843 var options = {};1844 controller.restart(options)1845 .then(() => {1846 test.equal(this.standardTesselCommand.lastCall.args[0], options);1847 test.equal(this.restart.callCount, 1);1848 test.done();1849 });1850 },1851};1852exports['controller.eraseScript'] = {1853 setUp(done) {1854 this.sandbox = sinon.sandbox.create();1855 this.spinnerStart = this.sandbox.stub(log.spinner, 'start');1856 this.spinnerStop = this.sandbox.stub(log.spinner, 'stop');1857 this.warn = this.sandbox.stub(log, 'warn');1858 this.info = this.sandbox.stub(log, 'info');1859 this.basic = this.sandbox.stub(log, 'basic');1860 this.error = this.sandbox.stub(log, 'error');1861 this.tessel = TesselSimulator({1862 name: 'TestTessel'1863 });1864 this.eraseScript = this.sandbox.stub(this.tessel, 'eraseScript').returns(Promise.resolve());1865 this.standardTesselCommand = this.sandbox.stub(controller, 'standardTesselCommand').callsFake((options, callback) => {1866 return callback(this.tessel);1867 });1868 done();1869 },1870 tearDown(done) {1871 this.tessel.mockClose();1872 this.sandbox.restore();1873 done();1874 },1875 eraseScriptCallPipeline(test) {1876 test.expect(2);1877 var options = {};1878 controller.eraseScript(options)1879 .then(() => {1880 test.equal(this.standardTesselCommand.lastCall.args[0], options);1881 test.equal(this.eraseScript.callCount, 1);1882 test.done();1883 });1884 },1885};1886exports['controller.setWiFiState'] = {1887 setUp(done) {1888 this.sandbox = sinon.sandbox.create();1889 this.spinnerStart = this.sandbox.stub(log.spinner, 'start');1890 this.spinnerStop = this.sandbox.stub(log.spinner, 'stop');1891 this.warn = this.sandbox.stub(log, 'warn');1892 this.info = this.sandbox.stub(log, 'info');1893 this.basic = this.sandbox.stub(log, 'basic');1894 this.error = this.sandbox.stub(log, 'error');1895 this.tessel = TesselSimulator({1896 name: 'TestTessel'1897 });1898 this.setWiFiState = this.sandbox.stub(this.tessel, 'setWiFiState').returns(Promise.resolve());1899 this.standardTesselCommand = this.sandbox.stub(controller, 'standardTesselCommand').callsFake((options, callback) => {1900 return callback(this.tessel);1901 });1902 done();1903 },1904 tearDown(done) {1905 this.tessel.mockClose();1906 this.sandbox.restore();1907 done();1908 },1909 setWiFiStateCallPipeline(test) {1910 test.expect(2);1911 var options = {};1912 controller.setWiFiState(options)1913 .then(() => {1914 test.equal(this.standardTesselCommand.lastCall.args[0], options);1915 test.equal(this.setWiFiState.callCount, 1);1916 test.done();1917 });1918 },1919 setWiFiStateMissingEnable(test) {1920 test.expect(1);1921 this.setWiFiState.restore();1922 controller.setWiFiState({})1923 .then(() => {1924 test.ok(false, 'This should not be successful');1925 test.done();1926 }).catch(error => {1927 test.equal(error.toString(), 'Error: Missing Wifi State: property "enable" not provided.');1928 test.done();1929 });1930 },1931};1932exports['controller.disableAccessPoint'] = {1933 setUp(done) {1934 this.sandbox = sinon.sandbox.create();1935 this.spinnerStart = this.sandbox.stub(log.spinner, 'start');1936 this.spinnerStop = this.sandbox.stub(log.spinner, 'stop');1937 this.warn = this.sandbox.stub(log, 'warn');1938 this.info = this.sandbox.stub(log, 'info');1939 this.basic = this.sandbox.stub(log, 'basic');1940 this.error = this.sandbox.stub(log, 'error');1941 this.tessel = TesselSimulator({1942 name: 'TestTessel'1943 });1944 this.disableAccessPoint = this.sandbox.stub(this.tessel, 'disableAccessPoint').returns(Promise.resolve());1945 this.standardTesselCommand = this.sandbox.stub(controller, 'standardTesselCommand').callsFake((options, callback) => {1946 return callback(this.tessel);1947 });1948 done();1949 },1950 tearDown(done) {1951 this.tessel.mockClose();1952 this.sandbox.restore();1953 done();1954 },1955 disableAccessPointCallPipeline(test) {1956 test.expect(2);1957 var options = {};1958 controller.disableAccessPoint(options)1959 .then(() => {1960 test.equal(this.standardTesselCommand.lastCall.args[0], options);1961 test.equal(this.disableAccessPoint.callCount, 1);1962 test.done();1963 });1964 },1965};1966exports['controller.enableAccessPoint'] = {1967 setUp(done) {1968 this.sandbox = sinon.sandbox.create();1969 this.spinnerStart = this.sandbox.stub(log.spinner, 'start');1970 this.spinnerStop = this.sandbox.stub(log.spinner, 'stop');1971 this.warn = this.sandbox.stub(log, 'warn');1972 this.info = this.sandbox.stub(log, 'info');1973 this.basic = this.sandbox.stub(log, 'basic');1974 this.error = this.sandbox.stub(log, 'error');1975 this.tessel = TesselSimulator({1976 name: 'TestTessel'1977 });1978 this.enableAccessPoint = this.sandbox.stub(this.tessel, 'enableAccessPoint').returns(Promise.resolve());1979 this.standardTesselCommand = this.sandbox.stub(controller, 'standardTesselCommand').callsFake((options, callback) => {1980 return callback(this.tessel);1981 });1982 done();1983 },1984 tearDown(done) {1985 this.tessel.mockClose();1986 this.sandbox.restore();1987 done();1988 },1989 enableAccessPointCallPipeline(test) {1990 test.expect(2);1991 var options = {};1992 controller.enableAccessPoint(options)1993 .then(() => {1994 test.equal(this.standardTesselCommand.lastCall.args[0], options);1995 test.equal(this.enableAccessPoint.callCount, 1);1996 test.done();1997 });1998 },1999};2000exports['controller.rename'] = {2001 setUp(done) {2002 this.sandbox = sinon.sandbox.create();2003 this.spinnerStart = this.sandbox.stub(log.spinner, 'start');2004 this.spinnerStop = this.sandbox.stub(log.spinner, 'stop');2005 this.warn = this.sandbox.stub(log, 'warn');2006 this.info = this.sandbox.stub(log, 'info');2007 this.basic = this.sandbox.stub(log, 'basic');2008 this.error = this.sandbox.stub(log, 'error');2009 this.tessel = TesselSimulator({2010 name: 'TestTessel'2011 });2012 this.rename = this.sandbox.stub(this.tessel, 'rename').returns(Promise.resolve());2013 this.standardTesselCommand = this.sandbox.stub(controller, 'standardTesselCommand').callsFake((options, callback) => {2014 return callback(this.tessel);2015 });2016 colors.enabled = false;2017 done();2018 },2019 tearDown(done) {2020 this.tessel.mockClose();2021 this.sandbox.restore();2022 colors.enabled = true;2023 done();2024 },2025 willNotRenameSameAsCurrent(test) {2026 test.expect(2);2027 var options = {2028 newName: this.tessel.name,2029 };2030 controller.rename(options)2031 .then(() => {2032 // Assert that a warning was logged when2033 // the new name is the same as the old name2034 test.equal(this.warn.callCount, 1);2035 test.equal(this.warn.lastCall.args[0], 'Name of device is already TestTessel');2036 test.done();2037 });2038 },2039 renameCallPipeline(test) {2040 test.expect(4);2041 var options = {2042 // reset: true,2043 newName: 'Valid',2044 };2045 controller.rename(options)2046 .then(() => {2047 test.equal(this.standardTesselCommand.lastCall.args[0], options);2048 test.equal(this.info.callCount, 1);2049 test.equal(this.info.lastCall.args[0], 'Renaming TestTessel to Valid');2050 test.equal(this.rename.callCount, 1);2051 test.done();2052 });2053 },...

Full Screen

Full Screen

parser-fa605265.js

Source:parser-fa605265.js Github

copy

Full Screen

1import { _ as __extends } from './webapi-dc144dc6.js';2import { c as cordova$1, e as Injectable, I as IonicNativePlugin, b as cordovaPropertyGet, d as cordovaPropertySet, O as Observable, m as msg, u as util } from './messages-bded0bf9.js';3import { j as jquery } from './jquery-ad132f97.js';4var LocationAccuracy = /** @class */ (function (_super) {5 __extends(LocationAccuracy, _super);6 function LocationAccuracy() {7 var _this = _super !== null && _super.apply(this, arguments) || this;8 /**9 * Convenience constant10 * @type {number}11 */12 _this.REQUEST_PRIORITY_NO_POWER = 0;13 /**14 * Convenience constant15 * @type {number}16 */17 _this.REQUEST_PRIORITY_LOW_POWER = 1;18 /**19 * Convenience constant20 * @type {number}21 */22 _this.REQUEST_PRIORITY_BALANCED_POWER_ACCURACY = 2;23 /**24 * Convenience constant25 * @type {number}26 */27 _this.REQUEST_PRIORITY_HIGH_ACCURACY = 3;28 /**29 * Convenience constant30 * @type {number}31 */32 _this.SUCCESS_SETTINGS_SATISFIED = 0;33 /**34 * Convenience constant35 * @type {number}36 */37 _this.SUCCESS_USER_AGREED = 1;38 /**39 * Convenience constant40 * @type {number}41 */42 _this.ERROR_ALREADY_REQUESTING = -1;43 /**44 * Convenience constant45 * @type {number}46 */47 _this.ERROR_INVALID_ACTION = 0;48 /**49 * Convenience constant50 * @type {number}51 */52 _this.ERROR_INVALID_ACCURACY = 1;53 /**54 * Convenience constant55 * @type {number}56 */57 _this.ERROR_EXCEPTION = 1;58 /**59 * Convenience constant60 * @type {number}61 */62 _this.ERROR_CANNOT_CHANGE_ACCURACY = 3;63 /**64 * Convenience constant65 * @type {number}66 */67 _this.ERROR_USER_DISAGREED = 4;68 /**69 * Convenience constant70 * @type {number}71 */72 _this.ERROR_GOOGLE_API_CONNECTION_FAILED = 4;73 return _this;74 }75 LocationAccuracy.prototype.canRequest = function () { return cordova$1(this, "canRequest", {}, arguments); };76 LocationAccuracy.prototype.isRequesting = function () { return cordova$1(this, "isRequesting", {}, arguments); };77 LocationAccuracy.prototype.request = function (accuracy) { return cordova$1(this, "request", { "callbackOrder": "reverse" }, arguments); };78 LocationAccuracy.pluginName = "LocationAccuracy";79 LocationAccuracy.plugin = "cordova-plugin-request-location-accuracy";80 LocationAccuracy.pluginRef = "cordova.plugins.locationAccuracy";81 LocationAccuracy.repo = "https://github.com/dpa99c/cordova-plugin-request-location-accuracy";82 LocationAccuracy.platforms = ["Android", "iOS"];83 LocationAccuracy.decorators = [84 { type: Injectable }85 ];86 return LocationAccuracy;87}(IonicNativePlugin));88var Diagnostic = /** @class */ (function (_super) {89 __extends(Diagnostic, _super);90 function Diagnostic() {91 var _this = _super !== null && _super.apply(this, arguments) || this;92 _this.permission = {93 READ_CALENDAR: 'READ_CALENDAR',94 WRITE_CALENDAR: 'WRITE_CALENDAR',95 CAMERA: 'CAMERA',96 READ_CONTACTS: 'READ_CONTACTS',97 WRITE_CONTACTS: 'WRITE_CONTACTS',98 GET_ACCOUNTS: 'GET_ACCOUNTS',99 ACCESS_FINE_LOCATION: 'ACCESS_FINE_LOCATION',100 ACCESS_COARSE_LOCATION: 'ACCESS_COARSE_LOCATION',101 RECORD_AUDIO: 'RECORD_AUDIO',102 READ_PHONE_STATE: 'READ_PHONE_STATE',103 CALL_PHONE: 'CALL_PHONE',104 ADD_VOICEMAIL: 'ADD_VOICEMAIL',105 USE_SIP: 'USE_SIP',106 PROCESS_OUTGOING_CALLS: 'PROCESS_OUTGOING_CALLS',107 READ_CALL_LOG: 'READ_CALL_LOG',108 WRITE_CALL_LOG: 'WRITE_CALL_LOG',109 SEND_SMS: 'SEND_SMS',110 RECEIVE_SMS: 'RECEIVE_SMS',111 READ_SMS: 'READ_SMS',112 RECEIVE_WAP_PUSH: 'RECEIVE_WAP_PUSH',113 RECEIVE_MMS: 'RECEIVE_MMS',114 WRITE_EXTERNAL_STORAGE: 'WRITE_EXTERNAL_STORAGE',115 READ_EXTERNAL_STORAGE: 'READ_EXTERNAL_STORAGE',116 BODY_SENSORS: 'BODY_SENSORS',117 };118 _this.locationAuthorizationMode = {119 ALWAYS: 'always',120 WHEN_IN_USE: 'when_in_use',121 };122 _this.permissionGroups = {123 CALENDAR: ['READ_CALENDAR', 'WRITE_CALENDAR'],124 CAMERA: ['CAMERA'],125 CONTACTS: ['READ_CONTACTS', 'WRITE_CONTACTS', 'GET_ACCOUNTS'],126 LOCATION: ['ACCESS_FINE_LOCATION', 'ACCESS_COARSE_LOCATION'],127 MICROPHONE: ['RECORD_AUDIO'],128 PHONE: [129 'READ_PHONE_STATE',130 'CALL_PHONE',131 'ADD_VOICEMAIL',132 'USE_SIP',133 'PROCESS_OUTGOING_CALLS',134 'READ_CALL_LOG',135 'WRITE_CALL_LOG',136 ],137 SENSORS: ['BODY_SENSORS'],138 SMS: ['SEND_SMS', 'RECEIVE_SMS', 'READ_SMS', 'RECEIVE_WAP_PUSH', 'RECEIVE_MMS'],139 STORAGE: ['READ_EXTERNAL_STORAGE', 'WRITE_EXTERNAL_STORAGE'],140 };141 _this.locationMode = {142 HIGH_ACCURACY: 'high_accuracy',143 DEVICE_ONLY: 'device_only',144 BATTERY_SAVING: 'battery_saving',145 LOCATION_OFF: 'location_off',146 };147 _this.bluetoothState = {148 UNKNOWN: 'unknown',149 RESETTING: 'resetting',150 UNSUPPORTED: 'unsupported',151 UNAUTHORIZED: 'unauthorized',152 POWERED_OFF: 'powered_off',153 POWERED_ON: 'powered_on',154 POWERING_OFF: 'powering_off',155 POWERING_ON: 'powering_on',156 };157 return _this;158 }159 Diagnostic.prototype.isLocationAvailable = function () { return cordova$1(this, "isLocationAvailable", {}, arguments); };160 Diagnostic.prototype.isWifiAvailable = function () { return cordova$1(this, "isWifiAvailable", {}, arguments); };161 Diagnostic.prototype.isCameraAvailable = function (externalStorage) { return cordova$1(this, "isCameraAvailable", { "callbackOrder": "reverse" }, arguments); };162 Diagnostic.prototype.isBluetoothAvailable = function () { return cordova$1(this, "isBluetoothAvailable", {}, arguments); };163 Diagnostic.prototype.switchToLocationSettings = function () { return cordova$1(this, "switchToLocationSettings", { "sync": true, "platforms": ["Android", "Windows 10", "iOS"] }, arguments); };164 Diagnostic.prototype.switchToMobileDataSettings = function () { return cordova$1(this, "switchToMobileDataSettings", { "sync": true, "platforms": ["Android", "Windows 10"] }, arguments); };165 Diagnostic.prototype.switchToBluetoothSettings = function () { return cordova$1(this, "switchToBluetoothSettings", { "sync": true, "platforms": ["Android", "Windows 10"] }, arguments); };166 Diagnostic.prototype.switchToWifiSettings = function () { return cordova$1(this, "switchToWifiSettings", { "sync": true, "platforms": ["Android", "Windows 10"] }, arguments); };167 Diagnostic.prototype.isWifiEnabled = function () { return cordova$1(this, "isWifiEnabled", { "platforms": ["Android", "Windows 10"] }, arguments); };168 Diagnostic.prototype.setWifiState = function (state) { return cordova$1(this, "setWifiState", { "callbackOrder": "reverse", "platforms": ["Android", "Windows 10"] }, arguments); };169 Diagnostic.prototype.setBluetoothState = function (state) { return cordova$1(this, "setBluetoothState", { "callbackOrder": "reverse", "platforms": ["Android", "Windows 10"] }, arguments); };170 Diagnostic.prototype.isLocationEnabled = function () { return cordova$1(this, "isLocationEnabled", { "platforms": ["Android", "iOS"] }, arguments); };171 Diagnostic.prototype.isLocationAuthorized = function () { return cordova$1(this, "isLocationAuthorized", {}, arguments); };172 Diagnostic.prototype.getLocationAuthorizationStatus = function () { return cordova$1(this, "getLocationAuthorizationStatus", { "platforms": ["Android", "iOS"] }, arguments); };173 Diagnostic.prototype.requestLocationAuthorization = function (mode) { return cordova$1(this, "requestLocationAuthorization", { "platforms": ["Android", "iOS"], "callbackOrder": "reverse" }, arguments); };174 Diagnostic.prototype.isCameraPresent = function () { return cordova$1(this, "isCameraPresent", { "platforms": ["Android", "iOS"] }, arguments); };175 Diagnostic.prototype.isCameraAuthorized = function (externalStorage) { return cordova$1(this, "isCameraAuthorized", { "platforms": ["Android", "iOS"], "callbackOrder": "reverse" }, arguments); };176 Diagnostic.prototype.getCameraAuthorizationStatus = function (externalStorage) { return cordova$1(this, "getCameraAuthorizationStatus", { "platforms": ["Android", "iOS"], "callbackOrder": "reverse" }, arguments); };177 Diagnostic.prototype.requestCameraAuthorization = function (externalStorage) { return cordova$1(this, "requestCameraAuthorization", { "platforms": ["Android", "iOS"], "callbackOrder": "reverse" }, arguments); };178 Diagnostic.prototype.isMicrophoneAuthorized = function () { return cordova$1(this, "isMicrophoneAuthorized", { "platforms": ["Android", "iOS"] }, arguments); };179 Diagnostic.prototype.getMicrophoneAuthorizationStatus = function () { return cordova$1(this, "getMicrophoneAuthorizationStatus", { "platforms": ["Android", "iOS"] }, arguments); };180 Diagnostic.prototype.requestMicrophoneAuthorization = function () { return cordova$1(this, "requestMicrophoneAuthorization", { "platforms": ["Android", "iOS"] }, arguments); };181 Diagnostic.prototype.isContactsAuthorized = function () { return cordova$1(this, "isContactsAuthorized", { "platforms": ["Android", "iOS"] }, arguments); };182 Diagnostic.prototype.getContactsAuthorizationStatus = function () { return cordova$1(this, "getContactsAuthorizationStatus", { "platforms": ["Android", "iOS"] }, arguments); };183 Diagnostic.prototype.requestContactsAuthorization = function () { return cordova$1(this, "requestContactsAuthorization", { "platforms": ["Android", "iOS"] }, arguments); };184 Diagnostic.prototype.isCalendarAuthorized = function () { return cordova$1(this, "isCalendarAuthorized", { "platforms": ["Android", "iOS"] }, arguments); };185 Diagnostic.prototype.getCalendarAuthorizationStatus = function () { return cordova$1(this, "getCalendarAuthorizationStatus", { "platforms": ["Android", "iOS"] }, arguments); };186 Diagnostic.prototype.requestCalendarAuthorization = function () { return cordova$1(this, "requestCalendarAuthorization", { "platforms": ["Android", "iOS"] }, arguments); };187 Diagnostic.prototype.switchToSettings = function () { return cordova$1(this, "switchToSettings", { "platforms": ["Android", "iOS"] }, arguments); };188 Diagnostic.prototype.getBluetoothState = function () { return cordova$1(this, "getBluetoothState", { "platforms": ["Android", "iOS"] }, arguments); };189 Diagnostic.prototype.registerBluetoothStateChangeHandler = function (handler) { return cordova$1(this, "registerBluetoothStateChangeHandler", { "platforms": ["Android", "iOS"], "sync": true }, arguments); };190 Diagnostic.prototype.registerLocationStateChangeHandler = function (handler) { return cordova$1(this, "registerLocationStateChangeHandler", { "platforms": ["Android", "iOS"], "sync": true }, arguments); };191 Diagnostic.prototype.isGpsLocationAvailable = function () { return cordova$1(this, "isGpsLocationAvailable", { "platforms": ["Android"] }, arguments); };192 Diagnostic.prototype.isGpsLocationEnabled = function () { return cordova$1(this, "isGpsLocationEnabled", { "platforms": ["Android"] }, arguments); };193 Diagnostic.prototype.isNetworkLocationAvailable = function () { return cordova$1(this, "isNetworkLocationAvailable", { "platforms": ["Android"] }, arguments); };194 Diagnostic.prototype.isNetworkLocationEnabled = function () { return cordova$1(this, "isNetworkLocationEnabled", { "platforms": ["Android"] }, arguments); };195 Diagnostic.prototype.getLocationMode = function () { return cordova$1(this, "getLocationMode", { "platforms": ["Android"] }, arguments); };196 Diagnostic.prototype.getPermissionAuthorizationStatus = function (permission) { return cordova$1(this, "getPermissionAuthorizationStatus", { "platforms": ["Android"], "callbackOrder": "reverse" }, arguments); };197 Diagnostic.prototype.getPermissionsAuthorizationStatus = function (permissions) { return cordova$1(this, "getPermissionsAuthorizationStatus", { "platforms": ["Android"], "callbackOrder": "reverse" }, arguments); };198 Diagnostic.prototype.requestRuntimePermission = function (permission) { return cordova$1(this, "requestRuntimePermission", { "platforms": ["Android"], "callbackOrder": "reverse" }, arguments); };199 Diagnostic.prototype.requestRuntimePermissions = function (permissions) { return cordova$1(this, "requestRuntimePermissions", { "platforms": ["Android"], "callbackOrder": "reverse" }, arguments); };200 Diagnostic.prototype.isRequestingPermission = function () { return cordova$1(this, "isRequestingPermission", { "sync": true }, arguments); };201 Diagnostic.prototype.registerPermissionRequestCompleteHandler = function (handler) { return cordova$1(this, "registerPermissionRequestCompleteHandler", { "sync": true }, arguments); };202 Diagnostic.prototype.isBluetoothEnabled = function () { return cordova$1(this, "isBluetoothEnabled", { "platforms": ["Android"] }, arguments); };203 Diagnostic.prototype.hasBluetoothSupport = function () { return cordova$1(this, "hasBluetoothSupport", { "platforms": ["Android"] }, arguments); };204 Diagnostic.prototype.hasBluetoothLESupport = function () { return cordova$1(this, "hasBluetoothLESupport", { "platforms": ["Android"] }, arguments); };205 Diagnostic.prototype.hasBluetoothLEPeripheralSupport = function () { return cordova$1(this, "hasBluetoothLEPeripheralSupport", { "platforms": ["Android"] }, arguments); };206 Diagnostic.prototype.isExternalStorageAuthorized = function () { return cordova$1(this, "isExternalStorageAuthorized", { "platforms": ["Android"] }, arguments); };207 Diagnostic.prototype.getExternalStorageAuthorizationStatus = function () { return cordova$1(this, "getExternalStorageAuthorizationStatus", { "platforms": ["Android"] }, arguments); };208 Diagnostic.prototype.requestExternalStorageAuthorization = function () { return cordova$1(this, "requestExternalStorageAuthorization", { "platforms": ["Android"] }, arguments); };209 Diagnostic.prototype.getExternalSdCardDetails = function () { return cordova$1(this, "getExternalSdCardDetails", { "platforms": ["Android"] }, arguments); };210 Diagnostic.prototype.switchToWirelessSettings = function () { return cordova$1(this, "switchToWirelessSettings", { "platforms": ["Android"], "sync": true }, arguments); };211 Diagnostic.prototype.switchToNFCSettings = function () { return cordova$1(this, "switchToNFCSettings", { "platforms": ["Android"], "sync": true }, arguments); };212 Diagnostic.prototype.isNFCPresent = function () { return cordova$1(this, "isNFCPresent", { "platforms": ["Android"] }, arguments); };213 Diagnostic.prototype.isNFCEnabled = function () { return cordova$1(this, "isNFCEnabled", { "platforms": ["Android"] }, arguments); };214 Diagnostic.prototype.isNFCAvailable = function () { return cordova$1(this, "isNFCAvailable", { "platforms": ["Android"] }, arguments); };215 Diagnostic.prototype.registerNFCStateChangeHandler = function (handler) { return cordova$1(this, "registerNFCStateChangeHandler", { "platforms": ["Android"], "sync": true }, arguments); };216 Diagnostic.prototype.isDataRoamingEnabled = function () { return cordova$1(this, "isDataRoamingEnabled", { "platforms": ["Android"] }, arguments); };217 Diagnostic.prototype.isADBModeEnabled = function () { return cordova$1(this, "isADBModeEnabled", { "platforms": ["Android"] }, arguments); };218 Diagnostic.prototype.isDeviceRooted = function () { return cordova$1(this, "isDeviceRooted", { "platforms": ["Android"] }, arguments); };219 Diagnostic.prototype.isCameraRollAuthorized = function () { return cordova$1(this, "isCameraRollAuthorized", { "platforms": ["iOS"] }, arguments); };220 Diagnostic.prototype.getCameraRollAuthorizationStatus = function () { return cordova$1(this, "getCameraRollAuthorizationStatus", { "platforms": ["iOS"] }, arguments); };221 Diagnostic.prototype.requestCameraRollAuthorization = function () { return cordova$1(this, "requestCameraRollAuthorization", { "platforms": ["iOS"] }, arguments); };222 Diagnostic.prototype.isRemoteNotificationsEnabled = function () { return cordova$1(this, "isRemoteNotificationsEnabled", { "platforms": ["iOS", "Android"] }, arguments); };223 Diagnostic.prototype.isRegisteredForRemoteNotifications = function () { return cordova$1(this, "isRegisteredForRemoteNotifications", { "platforms": ["iOS"] }, arguments); };224 Diagnostic.prototype.getRemoteNotificationsAuthorizationStatus = function () { return cordova$1(this, "getRemoteNotificationsAuthorizationStatus", { "platforms": ["iOS"] }, arguments); };225 Diagnostic.prototype.requestRemoteNotificationsAuthorization = function (types, omitRegistration) { return cordova$1(this, "requestRemoteNotificationsAuthorization", { "platforms": ["iOS"] }, arguments); };226 Diagnostic.prototype.getRemoteNotificationTypes = function () { return cordova$1(this, "getRemoteNotificationTypes", { "platforms": ["iOS"] }, arguments); };227 Diagnostic.prototype.isRemindersAuthorized = function () { return cordova$1(this, "isRemindersAuthorized", { "platforms": ["iOS"] }, arguments); };228 Diagnostic.prototype.getRemindersAuthorizationStatus = function () { return cordova$1(this, "getRemindersAuthorizationStatus", { "platforms": ["iOS"] }, arguments); };229 Diagnostic.prototype.requestRemindersAuthorization = function () { return cordova$1(this, "requestRemindersAuthorization", { "platforms": ["iOS"] }, arguments); };230 Diagnostic.prototype.isBackgroundRefreshAuthorized = function () { return cordova$1(this, "isBackgroundRefreshAuthorized", { "platforms": ["iOS"] }, arguments); };231 Diagnostic.prototype.getBackgroundRefreshStatus = function () { return cordova$1(this, "getBackgroundRefreshStatus", { "platforms": ["iOS"] }, arguments); };232 Diagnostic.prototype.requestBluetoothAuthorization = function () { return cordova$1(this, "requestBluetoothAuthorization", { "platforms": ["iOS"] }, arguments); };233 Diagnostic.prototype.isMotionAvailable = function () { return cordova$1(this, "isMotionAvailable", { "platforms": ["iOS"] }, arguments); };234 Diagnostic.prototype.isMotionRequestOutcomeAvailable = function () { return cordova$1(this, "isMotionRequestOutcomeAvailable", { "platforms": ["iOS"] }, arguments); };235 Diagnostic.prototype.requestMotionAuthorization = function () { return cordova$1(this, "requestMotionAuthorization", { "platforms": ["iOS"] }, arguments); };236 Diagnostic.prototype.getMotionAuthorizationStatus = function () { return cordova$1(this, "getMotionAuthorizationStatus", { "platforms": ["iOS"] }, arguments); };237 Diagnostic.prototype.getLocationAccuracyAuthorization = function () { return cordova$1(this, "getLocationAccuracyAuthorization", { "platform": ["iOS"] }, arguments); };238 Diagnostic.prototype.requestTemporaryFullAccuracyAuthorization = function (purpose) { return cordova$1(this, "requestTemporaryFullAccuracyAuthorization", { "platforms": ["iOS"] }, arguments); };239 Diagnostic.prototype.registerLocationAccuracyAuthorizationChangeHandler = function (handler) { return cordova$1(this, "registerLocationAccuracyAuthorizationChangeHandler", { "platforms": ["iOS"], "sync": true }, arguments); };240 Object.defineProperty(Diagnostic.prototype, "permissionStatus", {241 get: function () { return cordovaPropertyGet(this, "permissionStatus"); },242 set: function (value) { cordovaPropertySet(this, "permissionStatus", value); },243 enumerable: false,244 configurable: true245 });246 Object.defineProperty(Diagnostic.prototype, "NFCState", {247 get: function () { return cordovaPropertyGet(this, "NFCState"); },248 set: function (value) { cordovaPropertySet(this, "NFCState", value); },249 enumerable: false,250 configurable: true251 });252 Object.defineProperty(Diagnostic.prototype, "motionStatus", {253 get: function () { return cordovaPropertyGet(this, "motionStatus"); },254 set: function (value) { cordovaPropertySet(this, "motionStatus", value); },255 enumerable: false,256 configurable: true257 });258 Diagnostic.pluginName = "Diagnostic";259 Diagnostic.plugin = "cordova.plugins.diagnostic";260 Diagnostic.pluginRef = "cordova.plugins.diagnostic";261 Diagnostic.repo = "https://github.com/dpa99c/cordova-diagnostic-plugin";262 Diagnostic.platforms = ["Android", "iOS", "Windows"];263 Diagnostic.decorators = [264 { type: Injectable }265 ];266 return Diagnostic;267}(IonicNativePlugin));268var OpenNativeSettings = /** @class */ (function (_super) {269 __extends(OpenNativeSettings, _super);270 function OpenNativeSettings() {271 return _super !== null && _super.apply(this, arguments) || this;272 }273 OpenNativeSettings.prototype.open = function (setting) { return cordova$1(this, "open", {}, arguments); };274 OpenNativeSettings.pluginName = "OpenNativeSettings";275 OpenNativeSettings.plugin = "cordova-open-native-settings";276 OpenNativeSettings.pluginRef = "cordova.plugins.settings";277 OpenNativeSettings.repo = "https://github.com/guyromb/Cordova-open-native-settings";278 OpenNativeSettings.platforms = ["Android", "iOS"];279 OpenNativeSettings.decorators = [280 { type: Injectable }281 ];282 return OpenNativeSettings;283}(IonicNativePlugin));284var Geolocation = /** @class */ (function (_super) {285 __extends(Geolocation, _super);286 function Geolocation() {287 return _super !== null && _super.apply(this, arguments) || this;288 }289 Geolocation.prototype.getCurrentPosition = function (options) { return cordova$1(this, "getCurrentPosition", { "callbackOrder": "reverse" }, arguments); };290 /**291 * Watch the current device's position. Clear the watch by unsubscribing from292 * Observable changes.293 *294 * ```typescript295 * const subscription = this.geolocation.watchPosition()296 * .filter((p) => p.coords !== undefined) //Filter Out Errors297 * .subscribe(position => {298 * console.log(position.coords.longitude + ' ' + position.coords.latitude);299 * });300 *301 * // To stop notifications302 * subscription.unsubscribe();303 * ```304 *305 * @param {GeolocationOptions} options The [geolocation options](https://developer.mozilla.org/en-US/docs/Web/API/PositionOptions).306 * @returns {Observable<Geoposition | PositionError>} Returns an Observable that notifies with the [position](https://developer.mozilla.org/en-US/docs/Web/API/Position) of the device, or errors.307 */308 Geolocation.prototype.watchPosition = function (options) {309 return new Observable(function (observer) {310 var watchId = navigator.geolocation.watchPosition(observer.next.bind(observer), observer.next.bind(observer), options);311 return function () { return navigator.geolocation.clearWatch(watchId); };312 });313 };314 Geolocation.pluginName = "Geolocation";315 Geolocation.plugin = "cordova-plugin-geolocation";316 Geolocation.pluginRef = "navigator.geolocation";317 Geolocation.repo = "https://github.com/apache/cordova-plugin-geolocation";318 Geolocation.install = "ionic cordova plugin add cordova-plugin-geolocation --variable GEOLOCATION_USAGE_DESCRIPTION=\"To locate you\"";319 Geolocation.installVariables = ["GEOLOCATION_USAGE_DESCRIPTION"];320 Geolocation.platforms = ["Amazon Fire OS", "Android", "Browser", "iOS", "Windows"];321 Geolocation.decorators = [322 { type: Injectable }323 ];324 return Geolocation;325}(IonicNativePlugin));326var gps;327(function (gps) {328 let locationAccuracy = new LocationAccuracy;329 let diagnostic = new Diagnostic;330 /* alert('position.coords.latitude: ' + position.coords.latitude + '\n' +331 'position.coords.longitude: ' + position.coords.longitude + '\n' +332 'position.coords.altitude: ' + position.coords.altitude + '\n' +333 'position.coords.accuracy: ' + position.coords.accuracy + '\n' +334 'position.coords.altitudeAccuracy: ' + position.coords.altitudeAccuracy + '\n' +335 'position.coords.heading: ' + position.coords.heading + '\n' +336 'position.coords.speed: ' + position.coords.speed + '\n' +337 'position.timestamp: ' + position.timestamp + '\n');338 */339 async function getCoords(geoTimeout = 10000, maximumAge = 10) {340 const geolocation = new Geolocation;341 return new Promise(async (resolve, reject) => {342 var geoOpt = { maximumAge: maximumAge, timeout: geoTimeout, enableHighAccuracy: true };343 let id = geolocation.watchPosition(geoOpt)344 .subscribe((pos) => {345 id.unsubscribe();346 if (pos.constructor.name === 'Geoposition' || pos.constructor.name === 'GeolocationPosition' || pos.constructor.name === 'Position')347 resolve(pos);348 else {349 getCoordsError(pos);350 reject(pos);351 }352 });353 });354 }355 gps.getCoords = getCoords;356 function getCoordsError(error) {357 if (error.code == 1) {358 msg.danger(util.translate('exceptions.gpsAccess'));359 }360 else if (error.code == 3) {361 msg.danger(util.translate('exceptions.gpstimeout'));362 }363 else {364 alert('code: ' + error.code + '\n' +365 'message: ' + error.message + '\n');366 }367 }368 function checkAndAskGPSPermissions() {369 diagnostic.isLocationAuthorized().then(async (result) => {370 if (await gpsOff()) {371 try {372 await locationAccuracy.request(locationAccuracy.REQUEST_PRIORITY_HIGH_ACCURACY);373 }374 catch (err) { }375 }376 if (!result)377 await diagnostic.requestLocationAuthorization();378 }, err => { msg.showError('Error requesting location permissions: ' + err); });379 }380 gps.checkAndAskGPSPermissions = checkAndAskGPSPermissions;381 function checkGPSPermission() {382 diagnostic.isLocationAuthorized().then(result => {383 if (result)384 activationMsg(true);385 else386 activationMsg(false);387 }, err => { msg.showError('Error requesting location permissions: ' + err); });388 }389 gps.checkGPSPermission = checkGPSPermission;390 function requestGPSPermission(actMsg) {391 diagnostic.requestLocationAuthorization().then((result) => {392 if (result === 'DENIED_ALWAYS') {393 let openNativeSettings = new OpenNativeSettings;394 openNativeSettings.open('location').then(async () => {395 if (await diagnostic.isLocationAuthorized())396 askToTurnOnGPS(actMsg);397 });398 }399 else if (result !== 'DENIED_ONCE')400 askToTurnOnGPS(actMsg);401 }, err => { if (err.code !== 4)402 msg.showError('Error requesting location permissions: ' + err.message); });403 }404 function askToTurnOnGPS(actMsg) {405 locationAccuracy.request(locationAccuracy.REQUEST_PRIORITY_HIGH_ACCURACY).then(() => { actMsg.dismiss(); }, err => { if (err.code !== 4)406 msg.showError('Error requesting location permissions: ' + err.message); });407 }408 async function activationMsg(permission) {409 if (await gpsOff() || !permission) {410 const actMsg = document.createElement('ion-alert');411 actMsg.header = util.translate("gps.activationMsg");412 actMsg.backdropDismiss = false;413 actMsg.buttons = [414 {415 text: util.translate('Activate'),416 handler: () => {417 if (permission)418 askToTurnOnGPS(actMsg);419 else420 requestGPSPermission(actMsg);421 return false;422 }423 }424 ];425 document.body.appendChild(actMsg);426 actMsg.present();427 }428 }429 async function gpsOff() {430 if (cordova.platformId === 'ios') {431 return await locationAccuracy.canRequest();432 }433 else {434 let mode = await diagnostic.getLocationMode();435 if (mode === diagnostic.locationMode.LOCATION_OFF)436 return true;437 else438 return false;439 }440 }441})(gps || (gps = {}));442var parser;443(function (parser) {444 var culture = 'es-es';445 async function recursiveCompile(json, template, conf, contextFunctions, lastTemplate, AddTimeZone = false) {446 let reg = /{{([^{}]+)}}/g;447 let hasMoreMatches = template.match(reg);448 culture = conf.user.currentUserCultureId;449 let retString = template;450 if (json) {451 retString = await parser.compile(json, retString, conf.resources, contextFunctions, AddTimeZone);452 }453 ;454 if (conf && conf.user) {455 retString = await parser.compile(conf.user, retString, conf.resources, contextFunctions, AddTimeZone);456 }457 ;458 if ((!lastTemplate || retString != lastTemplate) && hasMoreMatches != null) {459 retString = await parser.recursiveCompile(json, retString, conf, contextFunctions, retString, AddTimeZone);460 }461 return retString;462 }463 parser.recursiveCompile = recursiveCompile;464 async function compile(json, template, files, contextFunctions, AddTimeZone = false) {465 let reg = /{{([^{}]+)}}/g;466 let matches = template.match(reg);467 let retString = template;468 let defDateFormat = 'LL';469 if (matches != null) {470 json = lowerKeys(json);471 let contextVars = lowerKeys(this);472 for (let i = 0; i < matches.length; i++) {473 var skipReplace = false;474 let marker = matches[i];475 let rValue = '';476 let isFunction = false;477 if (marker.indexOf('(') != -1) {478 try {479 let fFunc = marker.substring(2, marker.length - 2).trim();480 let fName = fFunc.substring(0, fFunc.indexOf('(')).trim();481 if (contextFunctions && typeof contextFunctions[fName] === 'function' || typeof execDynamicCode.call(this, fName) === 'function') {482 isFunction = true;483 }484 }485 catch (e) {486 }487 }488 if (isFunction) {489 //Es una funcion javascript.490 let fFunc = marker.substring(2, marker.length - 2).trim();491 let fName = fFunc.substring(0, fFunc.indexOf('(')).trim();492 let fParams = this.splitParams(fFunc.substring(fFunc.indexOf('(') + 1, fFunc.lastIndexOf(')')).trim());493 for (let j = 0; j < fParams.length; j++) {494 let jKey = fParams[j].toLowerCase().trim();495 if ((jKey.startsWith("'") && jKey.endsWith("'")) || (jKey.startsWith('"') && jKey.endsWith('"'))) {496 fParams[j] = jKey.slice(1, -1);497 }498 else if (jKey.startsWith("[") && jKey.endsWith("]")) {499 fParams[j] = eval(jKey);500 }501 else if ((json && (typeof json[jKey] != 'undefined')) || (contextVars && (typeof contextVars[jKey] != 'undefined') && (contextVars[jKey] != null)) || jKey === 'json' || jKey === 'template' || jKey === 'contextfunctions') {502 let value;503 if (json && (typeof json[jKey] != 'undefined')) {504 value = parser.getValue(json[jKey]);505 }506 else if (jKey === 'json') {507 value = json;508 }509 else if (jKey === 'template') {510 value = template;511 }512 else if (jKey === 'contextfunctions') {513 value = contextFunctions;514 }515 else {516 value = contextVars[jKey];517 }518 fParams[j] = value;519 }520 }521 try {522 if (contextFunctions && typeof contextFunctions[fName] != 'undefined') {523 rValue = contextFunctions[fName].apply(contextFunctions, fParams);524 }525 else {526 let found = false;527 let fClass = fName.split('.');528 switch (fClass.length) {529 case 1:530 found = true;531 rValue = window[fClass[0]](...fParams);532 break;533 case 2:534 found = true;535 rValue = window[fClass[0]][fClass[1]](...fParams);536 break;537 case 3:538 found = true;539 rValue = window[fClass[0]][fClass[1]][fClass[2]](...fParams);540 break;541 case 4:542 found = true;543 rValue = window[fClass[0]][fClass[1]][fClass[2]][fClass[3]](...fParams);544 break;545 case 5:546 found = true;547 rValue = window[fClass[0]][fClass[1]][fClass[2]][fClass[3]][fClass[4]](...fParams);548 break;549 case 6:550 found = true;551 rValue = window[fClass[0]][fClass[1]][fClass[2]][fClass[3]][fClass[4]][fClass[5]](...fParams);552 break;553 }554 if (!found) {555 rValue = execDynamicCode.call(this, fName).apply(null, fParams);556 }557 }558 if (rValue instanceof Promise) {559 rValue = await Promise.resolve(rValue);560 }561 }562 catch (ex) {563 rValue = ex.message;564 }565 }566 else if (marker.indexOf('|') != -1) {567 //Lleva algún tipo de formato.568 let auxMarker = marker.substring(2, marker.length - 2).trim();569 let jKeyUp = auxMarker.split('|')[0];570 let propFormat = auxMarker.split('|')[1];571 let jKey = jKeyUp.toLowerCase();572 if (propFormat.toLowerCase() == 'file') {573 let found = false;574 for (let i = 0; i < files.length; i++) {575 if (files[i].FileName.toLowerCase() == jKeyUp.toLowerCase()) {576 found = true;577 rValue = 'data:' + files[i].MimeType + ';base64,' + files[i].B64;578 break;579 }580 }581 if (!found) {582 rValue = jKeyUp;583 }584 }585 else {586 if ((json && typeof json[jKey] != 'undefined') || (contextVars && typeof contextVars[jKey] != 'undefined') || (contextFunctions && typeof contextFunctions[jKeyUp] != 'undefined') || (jKey == 'currentdatetime') || (jKey == 'currentdate') || (jKey == 'currenttime') || (jKey == 'currenttime') || (jKey == 'newguid')) {587 if (jKey == 'currentdatetime' || jKey == 'currentdate' || jKey == 'currenttime') {588 rValue = moment().toDate();589 }590 else if (jKey == 'newguid') {591 rValue = util.GUID();592 }593 else if (json && typeof json[jKey] != 'undefined') {594 rValue = parser.getValue(json[jKey], 'Value');595 }596 else if (contextVars && typeof contextVars[jKey] != 'undefined') {597 rValue = contextVars[jKey];598 }599 else if (contextFunctions && typeof contextFunctions[jKeyUp] != 'undefined') {600 rValue = contextFunctions[jKeyUp];601 }602 let typeF = propFormat.toLowerCase();603 let strFormat = '';604 if (typeF.indexOf(':') != -1) {605 typeF = propFormat.substring(propFormat.indexOf(':'), 0).toLowerCase();606 strFormat = propFormat.substring(propFormat.indexOf(':') + 1);607 }608 if (typeF == 'date') {609 /*{{datevalue|date:LLL}*/610 if (strFormat == '') {611 strFormat = defDateFormat;612 }613 if (strFormat == 'W') {614 if (AddTimeZone) {615 rValue = moment(rValue).locale(culture).format();616 }617 else {618 rValue = moment.utc(rValue).locale(culture).format();619 }620 }621 else {622 if (rValue && rValue != '' && moment.utc(rValue).isValid()) {623 if (AddTimeZone) {624 rValue = moment(rValue).locale(culture).format(strFormat);625 }626 else {627 rValue = moment.utc(rValue).locale(culture).format(strFormat);628 }629 }630 else {631 rValue = '';632 }633 }634 }635 else if (typeF == 'fromnow') { /*{{datevalue|fromnow:LLL}*/636 if (rValue && rValue != '' && moment.utc(rValue).isValid()) {637 if (AddTimeZone) {638 rValue = moment(rValue).locale(culture).fromNow();639 }640 else {641 rValue = moment(moment.utc(rValue).format().split('+')[0]).locale(culture).fromNow();642 }643 }644 }645 else if (typeF == 'tonow') { /*{{datevalue|tonow:LLL}*/646 if (rValue && rValue != '' && moment.utc(rValue).isValid()) {647 if (AddTimeZone) {648 rValue = moment(rValue).locale(culture).toNow();649 }650 else {651 rValue = moment(moment.utc(rValue).format().split('+')[0]).locale(culture).toNow();652 }653 }654 }655 else if (typeF == 'decimal') { /*{{value|decimal:3}*/656 if (rValue && rValue != '' && jquery.isNumeric(rValue)) {657 if (strFormat && strFormat != '') {658 if (culture == 'es-ES') {659 rValue = parseFloat(parseFloat(rValue).toFixed(strFormat)).toLocaleString('ca-ES', { minimumFractionDigits: strFormat });660 }661 else {662 rValue = parseFloat(parseFloat(rValue).toFixed(strFormat)).toLocaleString(culture, { minimumFractionDigits: strFormat });663 }664 }665 else {666 if (culture == 'es-ES') {667 rValue = parseFloat(rValue).toLocaleString('ca-ES');668 }669 else {670 rValue = parseFloat(rValue).toLocaleString(culture);671 }672 }673 }674 }675 else if (typeF == 'switch') { /*{{value|switch:[true:icon-check,false:icon-noncheck,null:icon-cancel,else:]}*/676 let found = false;677 if (rValue == null) {678 rValue = 'null';679 }680 //Convert expresion into object681 let valuesTemp = strFormat.toString().trim();682 valuesTemp = valuesTemp.substring(1, valuesTemp.length - 1);683 valuesTemp = valuesTemp.split(',');684 let values = new Object();685 for (let z = 0; z < valuesTemp.length; z++) {686 let arrKey = valuesTemp[z].split(':')[0].toString().trim();687 let arrValue = valuesTemp[z].split(':')[1].toString().trim();688 values[arrKey] = arrValue;689 }690 for (let switchvalue in values) {691 if (switchvalue.toLowerCase() == rValue.toString().toLowerCase()) {692 rValue = values[switchvalue];693 found = true;694 break;695 }696 }697 if (!found && typeof values['else'] != 'undefined') {698 rValue = values['else'];699 if (rValue == 'null') {700 rValue = '';701 }702 }703 }704 else if (typeF == 'string') { /*{{str|string:lower}*/ /*{{str|string:upper}*/ /*{{str|string:255}*/705 if (rValue && rValue != '') {706 if (strFormat.toLowerCase() == 'lower') {707 rValue = rValue.toLowerCase();708 }709 else if (strFormat.toLowerCase() == 'upper') {710 rValue = rValue.toUpperCase();711 }712 else if (jquery.isNumeric(strFormat) && (rValue.length > parseFloat(strFormat))) {713 rValue = rValue.substring(0, parseFloat(strFormat)) + '...';714 }715 rValue = parser.replaceAll(rValue, '\n', '<br>');716 }717 else {718 rValue = '';719 }720 }721 else if (typeF == 'isnull') { /*{{str|isnull:value}*/722 let arrFormat = strFormat.split(',');723 if (rValue == null || rValue === '' || rValue == 'null') {724 rValue = arrFormat[0];725 }726 else if (arrFormat.length > 1) {727 rValue = strFormat.substring(strFormat.indexOf(',') + 1);728 }729 }730 else if (typeF == 'bool') { /*{{value|bool:'true value','false 0 empty or null value'}*/731 let arrFormat = strFormat.split(',');732 if (typeof rValue == 'undefined' || rValue == null || !rValue || rValue == '' || rValue == '0' || rValue.toString().toLowerCase() == 'false' || rValue.toString().toLowerCase() == 'null') {733 if (arrFormat.length > 1) {734 rValue = arrFormat[1];735 }736 else {737 rValue = '';738 }739 }740 else {741 rValue = arrFormat[0];742 }743 }744 else if (typeF == 'value') {745 if (rValue == null) {746 rValue = '';747 }748 }749 else if (typeF == 'html' || typeF == 'htmlattr') {750 rValue = escapeHtmlString(rValue, typeF == 'htmlattr');751 }752 else if (typeF == 'js') {753 rValue = escapeJsString(rValue);754 }755 else if (typeF == 'sql') {756 rValue = escapeSqltring(rValue);757 }758 }759 else {760 skipReplace = true;761 }762 }763 }764 else {765 //Es un marcador simple.766 let jKeyUp = marker.substring(2, marker.length - 2).trim();767 let jKey = jKeyUp.toLowerCase();768 if ((json && typeof json[jKey.toLowerCase()] != 'undefined') || (contextVars && typeof contextVars[jKey.toLowerCase()] != 'undefined') || (contextFunctions && typeof contextFunctions[jKeyUp] != 'undefined') || (jKey == 'currentdatetime') || (jKey == 'currentdate') || (jKey == 'currentlocation') || (jKey == 'currentaltitude') || (jKey == 'currentlongitude') || (jKey == 'currentlatitude') || (jKey == 'currenttime') || (jKey == 'newguid')) {769 if (jKey == 'currentdatetime') {770 rValue = util.currentDateTime();771 }772 else if (jKey == 'currentdate') {773 rValue = util.currentDate();774 }775 else if (jKey == 'currenttime') {776 rValue = util.currentTime();777 }778 else if (jKey == 'newguid') {779 rValue = util.GUID();780 }781 else if (jKey == 'currentlocation') {782 let pos = await gps.getCoords();783 rValue = pos.coords.latitude + ', ' + pos.coords.longitude;784 }785 else if (jKey == 'currentaltitude') {786 let pos = await gps.getCoords();787 rValue = pos.coords.altitude;788 }789 else if (jKey == 'currentlongitude') {790 let pos = await gps.getCoords();791 rValue = pos.coords.longitude;792 }793 else if (jKey == 'currentlatitude') {794 let pos = await gps.getCoords();795 rValue = pos.coords.latitude;796 }797 else if (json && typeof json[jKey] != 'undefined' && json[jKey] != null) {798 rValue = parser.getValue(json[jKey]);799 }800 else if (contextVars && typeof contextVars[jKey] != 'undefined') {801 rValue = contextVars[jKey];802 }803 else if (contextFunctions && typeof contextFunctions[jKeyUp] != 'undefined') {804 rValue = contextFunctions[jKeyUp];805 }806 }807 else {808 skipReplace = true;809 }810 if (typeof rValue == 'string' && rValue.indexOf('/Date') != -1) {811 rValue = moment(rValue).locale(culture).format(defDateFormat);812 }813 else if (typeof rValue == 'object' && rValue != null && rValue.Hours) {814 rValue = moment(rValue).utc().format('LTS');815 }816 if (rValue == null) {817 rValue = '';818 }819 }820 if (!skipReplace) {821 retString = parser.replaceAll(retString, marker, rValue);822 }823 }824 }825 return retString;826 }827 parser.compile = compile;828 function findTemplate(obj, typeId, pageName) {829 if (obj) {830 for (let i = 0; i < obj.pages.length; i++) {831 if (pageName) {832 if (obj.pages[i].pageName.toLowerCase() == pageName.toLowerCase()) {833 if (!obj.pages[i].SQLSentence) {834 obj.pages[i].SQLSentence = 'select * from ' + obj.tableName + ' where `' + obj.tableName + '`.`_isDeleted`=0';835 }836 return obj.pages[i];837 }838 }839 else {840 if (obj.pages[i].typeId.toLowerCase() == typeId.toLowerCase() && obj.pages[i].isDefault == true) {841 if (!obj.pages[i].SQLSentence) {842 obj.pages[i].SQLSentence = 'select * from ' + obj.tableName + ' where `' + obj.tableName + '`.`_isDeleted`=0';843 }844 return obj.pages[i];845 }846 }847 }848 }849 return null;850 }851 parser.findTemplate = findTemplate;852 function getValue(val, prop) {853 if (val == null) {854 return null;855 }856 let type = typeof val;857 type = type.toLocaleLowerCase();858 if (type == 'object') {859 if (prop) {860 return val[prop];861 }862 else {863 return val.Text;864 }865 }866 else {867 return val;868 }869 }870 parser.getValue = getValue;871 function replaceAll(str, find, replace) {872 if (!str || find == replace) {873 return str;874 }875 const escapeRegExp = (string) => {876 return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');877 };878 return str.toString().replace(new RegExp(escapeRegExp(find), 'ig'), replace);879 }880 parser.replaceAll = replaceAll;881 function formatDate(value) {882 return value;883 }884 parser.formatDate = formatDate;885 function formatNumber(value) {886 return value;887 }888 parser.formatNumber = formatNumber;889 function formatDecimal(value) {890 return value;891 }892 parser.formatDecimal = formatDecimal;893 /**894 * Returns an escaped JS string895 * @method escapeJsString896 * @param {string} str - String897*/898 function escapeJsString(str) {899 if (str) {900 str = replaceAll(str, '\\', '\\\\');901 str = replaceAll(str, '\'', '\\\'');902 str = replaceAll(str, "\"", '&quot;');903 }904 return str;905 }906 parser.escapeJsString = escapeJsString;907 /**908 * Returns an escaped SQL string909 * @method escapeSqlString910 * @param {string} str - String911 */912 function escapeSqltring(str) {913 if (str) {914 str = replaceAll(str, "'", "''");915 }916 return str;917 }918 parser.escapeSqltring = escapeSqltring;919 function splitParams(pStr) {920 let params = [];921 let newParam = '';922 let arrOpened = false;923 for (let i = 0; i < pStr.length; i++) {924 if (pStr[i] == ',' && !arrOpened) {925 params.push(newParam);926 newParam = '';927 }928 else {929 if (pStr[i] == '[') {930 arrOpened = true;931 }932 if (pStr[i] == ']') {933 arrOpened = false;934 }935 newParam += pStr[i];936 }937 }938 if (newParam) {939 params.push(newParam);940 }941 return params;942 }943 parser.splitParams = splitParams;944 /**945 * Returns an escapep HTML string946 * @method escapeHtmlString947 * @param {string} str - String948 * @param {boolean} attr - Determine if the line breaks are substituted949 */950 function escapeHtmlString(str, attr) {951 if (str) {952 str = replaceAll(str, '&', '&amp;');953 str = replaceAll(str, '<', '&lt;');954 str = replaceAll(str, '>', '&gt;');955 str = replaceAll(str, '"', '&quot');956 str = replaceAll(str, "'", '&#39;');957 str = replaceAll(str, ',', '&#44;');958 str = replaceAll(str, ':', '&#58;');959 str = replaceAll(str, '|', '&#124;');960 if (attr) {961 str = replaceAll(str, '\\', '\\\\');962 str = replaceAll(str, '\n', '');963 str = replaceAll(str, '\r', '');964 str = replaceAll(str, '&#39;', '\\\'');965 }966 }967 return str;968 }969 parser.escapeHtmlString = escapeHtmlString;970 /**971 * Transform object keys into lower case.972 * @param {object} obj - Object to transform.973 * @param {string} [recursive=false] - Set recursive mode on/off.974 * @method lowerKeys975 * @return {object} transformed object.976 */977 function lowerKeys(obj, recursive = false) {978 if (obj) {979 var key, keys = Object.keys(obj);980 var n = keys.length;981 var newobj = {};982 for (var i = 0; i < n; i++) {983 key = keys[i];984 if (recursive && (typeof obj[key] === "object") && (obj[key] !== null) && (key.toLowerCase() !== 'objectdefaults')) {985 newobj[key.toLowerCase()] = lowerKeys(obj[key], recursive);986 }987 else {988 newobj[key.toLowerCase()] = obj[key];989 }990 }991 return newobj;992 }993 else {994 return null;995 }996 }997 parser.lowerKeys = lowerKeys;998 /**999 * Evaluates JavaScript code and executes it.1000 * @param {string} dynamicCode - Dynamic Code.1001 * @method execDynamicCode1002 * @return {any}1003 */1004 function execDynamicCode(dynamicCode) {1005 return eval(dynamicCode);1006 /*jQuery.globalEval*/1007 }1008 parser.execDynamicCode = execDynamicCode;1009 /**1010 * Sorts an object's array by specified properties.1011 * @param {object} obj - Object to order.1012 * @param {string} property - Order property1013 * @param {string} [property2] - Second order property1014 * @method sortObject1015 * @return {any[]} Ordered object.1016 */1017 function sortObject(obj, property, property2) {1018 var sortable = [];1019 var key;1020 for (key in obj) {1021 sortable.push(obj[key]);1022 }1023 sortable.sort(function (a, b) {1024 var o1 = a[property];1025 var o2 = b[property];1026 if (o1 < o2)1027 return -1;1028 if (o1 > o2)1029 return 1;1030 if (property2) {1031 var p1 = a[property2];1032 var p2 = b[property2];1033 if (p1 < p2)1034 return -1;1035 if (p1 > p2)1036 return 1;1037 }1038 return 0;1039 });1040 return sortable;1041 }1042 parser.sortObject = sortObject;1043})(parser || (parser = {}));...

Full Screen

Full Screen

adb-commands.js

Source:adb-commands.js Github

copy

Full Screen

...681 * is an emulator rather than a real device.682 */683methods.setWifiAndData = async function ({wifi, data}, isEmulator = false) {684 if (!_.isUndefined(wifi)) {685 this.setWifiState(wifi, isEmulator);686 }687 if (!_.isUndefined(data)) {688 this.setDataState(data, isEmulator);689 }690};691/**692 * Change the state of animation on the device under test.693 * Animation on the device is controlled by the following global properties:694 * [ANIMATOR_DURATION_SCALE]{@link https://developer.android.com/reference/android/provider/Settings.Global.html#ANIMATOR_DURATION_SCALE},695 * [TRANSITION_ANIMATION_SCALE]{@link https://developer.android.com/reference/android/provider/Settings.Global.html#TRANSITION_ANIMATION_SCALE},696 * [WINDOW_ANIMATION_SCALE]{@link https://developer.android.com/reference/android/provider/Settings.Global.html#WINDOW_ANIMATION_SCALE}.697 * This method sets all this properties to 0.0 to disable (1.0 to enable) animation.698 *699 * Turning off animation might be useful to improve stability...

Full Screen

Full Screen

bin-tessel-2.js

Source:bin-tessel-2.js Github

copy

Full Screen

1// Test dependencies are required and exposed in common/bootstrap.js2require('../common/bootstrap');3// If the defaults are intentionally changed in bin-tessel-2,4// then they must be changed here as well. This ensures that the5// expected default command options are protected from regressions.6// This should be used as a guide for reviewing new tessel-centric7// additions to the cli command set.8/*global CrashReporter */9var defaults = {10 timeout: {11 abbr: 't',12 metavar: 'TIMEOUT',13 help: 'Set timeout in seconds for scanning for networked tessels',14 default: 5,15 name: 'timeout',16 },17 name: {18 metavar: 'NAME',19 help: 'The name of the tessel on which the command will be executed',20 name: 'name',21 },22 lan: {23 flag: true,24 help: 'Use only a LAN connection',25 name: 'lan',26 string: '--lan',27 },28 usb: {29 flag: true,30 help: 'Use only a USB connection',31 name: 'usb',32 string: '--usb',33 },34 lanPrefer: {35 flag: true,36 default: false,37 help: 'Prefer a LAN connection if it\'s available, otherwise use USB'38 }39};40exports['Tessel (t2: makeCommand)'] = {41 any(test) {42 test.expect(16);43 t2.makeCommand('any')44 .callback(function() {45 test.equal(this.specs.timeout.abbr, defaults.timeout.abbr);46 test.equal(this.specs.timeout.default, defaults.timeout.default);47 test.equal(this.specs.timeout.help, defaults.timeout.help);48 test.equal(this.specs.timeout.metavar, defaults.timeout.metavar);49 test.equal(this.specs.timeout.name, defaults.timeout.name);50 test.equal(this.specs.name.help, defaults.name.help);51 test.equal(this.specs.name.metavar, defaults.name.metavar);52 test.equal(this.specs.name.name, defaults.name.name);53 test.equal(this.specs.lan.flag, defaults.lan.flag);54 test.equal(this.specs.lan.help, defaults.lan.help);55 test.equal(this.specs.lan.string, defaults.lan.string);56 test.equal(this.specs.lan.name, defaults.lan.name);57 test.equal(this.specs.usb.flag, defaults.usb.flag);58 test.equal(this.specs.usb.help, defaults.usb.help);59 test.equal(this.specs.usb.string, defaults.usb.string);60 test.equal(this.specs.usb.name, defaults.usb.name);61 test.done();62 });63 t2(['any']);64 }65};66exports['Tessel (t2: restart)'] = {67 setUp(done) {68 this.sandbox = sinon.sandbox.create();69 this.spinnerStart = this.sandbox.stub(log.spinner, 'start');70 this.spinnerStop = this.sandbox.stub(log.spinner, 'stop');71 this.error = this.sandbox.stub(log, 'error');72 this.warn = this.sandbox.stub(log, 'warn');73 this.info = this.sandbox.stub(log, 'info');74 this.restart = this.sandbox.stub(controller, 'restart').returns(Promise.resolve());75 this.closeFailedCommand = this.sandbox.spy(t2, 'closeFailedCommand');76 this.closeSuccessfulCommand = this.sandbox.stub(t2, 'closeSuccessfulCommand');77 this.processExit = this.sandbox.stub(process, 'exit');78 done();79 },80 tearDown(done) {81 this.sandbox.restore();82 done();83 },84 noError(test) {85 test.expect(1);86 t2(['restart', '--entryPoint=index.js', '--type=ram']);87 test.equal(this.restart.callCount, 1);88 // We must wait for the command to complete89 // or else the sandbox will be cleared too early90 setImmediate(test.done);91 },92 exitCodeOne(test) {93 test.expect(4);94 var error = new Error('Some error happened.');95 var restartOp = Promise.reject(error);96 this.restart.returns(restartOp);97 t2(['restart', '--entryPoint=index.js', '--type=ram']);98 restartOp.catch(() => {99 test.equal(this.restart.callCount, 1);100 test.equal(this.closeFailedCommand.callCount, 1);101 test.equal(this.closeFailedCommand.lastCall.args[0], error);102 test.equal(this.processExit.lastCall.args[0], 1);103 test.done();104 });105 },106 invalidType(test) {107 test.expect(4);108 t2(['restart', '--entryPoint=index.js', '--type=any']);109 setImmediate(() => {110 // Calling restart should not be reached111 test.equal(this.restart.callCount, 0);112 test.equal(this.closeFailedCommand.callCount, 1);113 test.equal(this.closeFailedCommand.lastCall.args[0].trim(), '--type Invalid');114 test.equal(this.processExit.lastCall.args[0], 1);115 test.done();116 });117 },118 entryPointFallbackToPrevious(test) {119 test.expect(1);120 var restartOp = Promise.resolve();121 this.sandbox.stub(Preferences, 'read').returns(Promise.resolve('previous.js'));122 t2(['restart']);123 this.restart.returns(restartOp);124 restartOp.then(() => {125 test.equal(this.restart.lastCall.args[0].entryPoint, 'previous.js');126 test.done();127 });128 },129 entryPointFallbackNoPrevious(test) {130 test.expect(1);131 this.closeFailedCommand.restore();132 this.closeFailedCommand = this.sandbox.stub(t2, 'closeFailedCommand');133 var resolved = Promise.resolve('');134 this.sandbox.stub(Preferences, 'read').returns(resolved);135 t2(['restart']);136 resolved.then(() => {137 test.equal(this.closeFailedCommand.lastCall.args[0], 'Cannot determine entry point file name');138 test.done();139 });140 },141 entryPointFallbackNoPreviousUndefined(test) {142 test.expect(1);143 this.closeFailedCommand.restore();144 this.closeFailedCommand = this.sandbox.stub(t2, 'closeFailedCommand');145 var resolved = Promise.resolve(undefined);146 this.sandbox.stub(Preferences, 'read').returns(resolved);147 t2(['restart']);148 resolved.then(() => {149 test.equal(this.closeFailedCommand.lastCall.args[0], 'Cannot determine entry point file name');150 test.done();151 });152 },153};154exports['Tessel (t2: update)'] = {155 setUp(done) {156 this.sandbox = sinon.sandbox.create();157 this.spinnerStart = this.sandbox.stub(log.spinner, 'start');158 this.spinnerStop = this.sandbox.stub(log.spinner, 'stop');159 this.error = this.sandbox.stub(log, 'error');160 this.warn = this.sandbox.stub(log, 'warn');161 this.printAvailableUpdates = this.sandbox.stub(controller, 'printAvailableUpdates').returns(Promise.resolve());162 this.update = this.sandbox.stub(controller, 'update').returns(Promise.resolve());163 this.closeFailedCommand = this.sandbox.spy(t2, 'closeFailedCommand');164 this.processExit = this.sandbox.stub(process, 'exit');165 done();166 },167 tearDown(done) {168 this.sandbox.restore();169 done();170 },171 optsForwarding(test) {172 test.expect(4);173 t2(['update', '--version', '42']);174 test.equal(this.update.callCount, 1);175 test.deepEqual(this.update.lastCall.args[0], {176 0: 'update',177 version: 42,178 _: ['update'],179 timeout: 5,180 lanPrefer: false,181 output: true,182 loglevel: 'basic',183 });184 t2(['update', '--list']);185 // controller.update is not called for --list,186 // so callCount remains 1187 test.equal(this.update.callCount, 1);188 test.equal(this.printAvailableUpdates.callCount, 1);189 // We must wait for the command to complete190 // or else the sandbox will be cleared to early191 setImmediate(test.done);192 },193 noError(test) {194 test.expect(1);195 t2(['update']);196 test.equal(this.update.callCount, 1);197 // We must wait for the command to complete198 // or else the sandbox will be cleared to early199 setImmediate(test.done);200 },201 exitCodeOne(test) {202 test.expect(4);203 var error = new Error('Some error happened.');204 var updateOp = Promise.reject(error);205 this.update.returns(updateOp);206 t2(['update']);207 updateOp.catch(() => {208 test.equal(this.update.callCount, 1);209 test.equal(this.closeFailedCommand.callCount, 1);210 test.equal(this.closeFailedCommand.lastCall.args[0], error);211 test.equal(this.processExit.lastCall.args[0], 1);212 test.done();213 });214 },215};216exports['Tessel (t2: restore)'] = {217 setUp(done) {218 this.sandbox = sinon.sandbox.create();219 this.spinnerStart = this.sandbox.stub(log.spinner, 'start');220 this.spinnerStop = this.sandbox.stub(log.spinner, 'stop');221 this.error = this.sandbox.stub(log, 'error');222 this.warn = this.sandbox.stub(log, 'warn');223 this.restore = this.sandbox.stub(controller, 'restore').returns(Promise.resolve());224 this.closeFailedCommand = this.sandbox.spy(t2, 'closeFailedCommand');225 this.processExit = this.sandbox.stub(process, 'exit');226 done();227 },228 tearDown(done) {229 this.sandbox.restore();230 done();231 },232 noError(test) {233 test.expect(1);234 t2(['restore']);235 setImmediate(() => {236 test.equal(this.restore.callCount, 1);237 test.done();238 });239 },240};241exports['Tessel (t2: version)'] = {242 setUp(done) {243 this.sandbox = sinon.sandbox.create();244 this.spinnerStart = this.sandbox.stub(log.spinner, 'start');245 this.spinnerStop = this.sandbox.stub(log.spinner, 'stop');246 this.error = this.sandbox.stub(log, 'error');247 this.warn = this.sandbox.stub(log, 'warn');248 this.envVersions = this.sandbox.stub(controller, 'envVersions').returns(Promise.resolve());249 this.closeFailedCommand = this.sandbox.spy(t2, 'closeFailedCommand');250 this.processExit = this.sandbox.stub(process, 'exit');251 done();252 },253 tearDown(done) {254 this.sandbox.restore();255 done();256 },257 noError(test) {258 test.expect(1);259 t2(['version']);260 setImmediate(() => {261 test.equal(this.envVersions.callCount, 1);262 test.done();263 });264 },265};266exports['Tessel (t2: rename)'] = {267 setUp(done) {268 this.sandbox = sinon.sandbox.create();269 this.spinnerStart = this.sandbox.stub(log.spinner, 'start');270 this.spinnerStop = this.sandbox.stub(log.spinner, 'stop');271 this.error = this.sandbox.stub(log, 'error');272 this.warn = this.sandbox.stub(log, 'warn');273 this.rename = this.sandbox.stub(controller, 'rename').returns(Promise.resolve());274 this.closeFailedCommand = this.sandbox.spy(t2, 'closeFailedCommand');275 this.processExit = this.sandbox.stub(process, 'exit');276 done();277 },278 tearDown(done) {279 this.sandbox.restore();280 done();281 },282 noError(test) {283 test.expect(1);284 t2(['rename']);285 setImmediate(() => {286 test.equal(this.rename.callCount, 1);287 test.done();288 });289 },290};291exports['Tessel (t2: key)'] = {292 setUp(done) {293 this.sandbox = sinon.sandbox.create();294 this.spinnerStart = this.sandbox.stub(log.spinner, 'start');295 this.spinnerStop = this.sandbox.stub(log.spinner, 'stop');296 this.error = this.sandbox.stub(log, 'error');297 this.warn = this.sandbox.stub(log, 'warn');298 this.setupLocal = this.sandbox.stub(controller, 'setupLocal').returns(Promise.resolve());299 this.closeFailedCommand = this.sandbox.spy(t2, 'closeFailedCommand');300 this.processExit = this.sandbox.stub(process, 'exit');301 done();302 },303 tearDown(done) {304 this.sandbox.restore();305 done();306 },307 noError(test) {308 test.expect(1);309 t2(['key', '--generate=1']);310 setImmediate(() => {311 test.equal(this.setupLocal.callCount, 1);312 test.done();313 });314 },315};316exports['Tessel (t2: ap)'] = {317 setUp(done) {318 this.sandbox = sinon.sandbox.create();319 this.spinnerStart = this.sandbox.stub(log.spinner, 'start');320 this.spinnerStop = this.sandbox.stub(log.spinner, 'stop');321 this.error = this.sandbox.stub(log, 'error');322 this.warn = this.sandbox.stub(log, 'warn');323 this.enableAccessPoint = this.sandbox.stub(controller, 'enableAccessPoint')324 .returns(Promise.resolve());325 this.disableAccessPoint = this.sandbox.stub(controller, 'disableAccessPoint')326 .returns(Promise.resolve());327 this.createAccessPoint = this.sandbox.stub(controller, 'createAccessPoint')328 .returns(Promise.resolve());329 this.getAccessPointInfo = this.sandbox.stub(controller, 'getAccessPointInfo')330 .returns(Promise.resolve());331 this.closeFailedCommand = this.sandbox.spy(t2, 'closeFailedCommand');332 this.processExit = this.sandbox.stub(process, 'exit');333 done();334 },335 tearDown(done) {336 this.sandbox.restore();337 done();338 },339 onNoError(test) {340 test.expect(1);341 t2(['ap', '--on']);342 setImmediate(() => {343 test.equal(this.enableAccessPoint.callCount, 1);344 test.done();345 });346 },347 offNoError(test) {348 test.expect(1);349 t2(['ap', '--off']);350 setImmediate(() => {351 test.equal(this.disableAccessPoint.callCount, 1);352 test.done();353 });354 },355 ssidNoError(test) {356 test.expect(1);357 t2(['ap', '--ssid=foo']);358 setImmediate(() => {359 test.equal(this.createAccessPoint.callCount, 1);360 test.done();361 });362 },363 requestSSIDNoError(test) {364 test.expect(1);365 t2(['ap']);366 setImmediate(() => {367 test.equal(this.getAccessPointInfo.callCount, 1);368 test.done();369 });370 },371};372exports['Tessel (t2: provision)'] = {373 setUp(done) {374 this.sandbox = sinon.sandbox.create();375 this.spinnerStart = this.sandbox.stub(log.spinner, 'start');376 this.spinnerStop = this.sandbox.stub(log.spinner, 'stop');377 this.error = this.sandbox.stub(log, 'error');378 this.warn = this.sandbox.stub(log, 'warn');379 this.info = this.sandbox.stub(log, 'info');380 this.provision = this.sandbox.stub(controller, 'provision').returns(Promise.resolve());381 this.closeFailedCommand = this.sandbox.spy(t2, 'closeFailedCommand');382 this.processExit = this.sandbox.stub(process, 'exit');383 done();384 },385 tearDown(done) {386 this.sandbox.restore();387 done();388 },389 noError(test) {390 test.expect(1);391 t2(['provision']);392 // We must wait for the command to complete393 // or else the sandbox will be cleared to early394 setImmediate(() => {395 test.equal(this.provision.callCount, 1);396 test.done();397 });398 },399 exitCodeOne(test) {400 test.expect(4);401 var error = new Error('Some error happened.');402 var provisionOp = Promise.reject(error);403 this.provision.returns(provisionOp);404 t2(['provision']);405 provisionOp.catch(() => {406 test.equal(this.provision.callCount, 1);407 test.equal(this.closeFailedCommand.callCount, 1);408 test.equal(this.closeFailedCommand.lastCall.args[0], error);409 test.equal(this.processExit.lastCall.args[0], 1);410 test.done();411 });412 },413};414exports['Tessel (t2: reboot)'] = {415 setUp(done) {416 this.sandbox = sinon.sandbox.create();417 this.spinnerStart = this.sandbox.stub(log.spinner, 'start');418 this.spinnerStop = this.sandbox.stub(log.spinner, 'stop');419 this.error = this.sandbox.stub(log, 'error');420 this.warn = this.sandbox.stub(log, 'warn');421 this.info = this.sandbox.stub(log, 'info');422 this.reboot = this.sandbox.stub(controller, 'reboot').returns(Promise.resolve());423 this.closeFailedCommand = this.sandbox.spy(t2, 'closeFailedCommand');424 this.processExit = this.sandbox.stub(process, 'exit');425 done();426 },427 tearDown(done) {428 this.sandbox.restore();429 done();430 },431 noError(test) {432 test.expect(1);433 t2(['reboot']);434 // We must wait for the command to complete435 // or else the sandbox will be cleared to early436 setImmediate(() => {437 test.equal(this.reboot.callCount, 1);438 test.done();439 });440 },441};442exports['Tessel (t2: erase)'] = {443 setUp(done) {444 this.sandbox = sinon.sandbox.create();445 this.spinnerStart = this.sandbox.stub(log.spinner, 'start');446 this.spinnerStop = this.sandbox.stub(log.spinner, 'stop');447 this.error = this.sandbox.stub(log, 'error');448 this.warn = this.sandbox.stub(log, 'warn');449 this.info = this.sandbox.stub(log, 'info');450 this.eraseScript = this.sandbox.stub(controller, 'eraseScript').returns(Promise.resolve());451 this.closeFailedCommand = this.sandbox.spy(t2, 'closeFailedCommand');452 this.processExit = this.sandbox.stub(process, 'exit');453 done();454 },455 tearDown(done) {456 this.sandbox.restore();457 done();458 },459 noError(test) {460 test.expect(1);461 t2(['erase']);462 // We must wait for the command to complete463 // or else the sandbox will be cleared to early464 setImmediate(() => {465 test.equal(this.eraseScript.callCount, 1);466 test.done();467 });468 },469};470exports['Tessel (t2: wifi)'] = {471 setUp(done) {472 this.sandbox = sinon.sandbox.create();473 this.spinnerStart = this.sandbox.stub(log.spinner, 'start');474 this.spinnerStop = this.sandbox.stub(log.spinner, 'stop');475 this.warn = this.sandbox.stub(log, 'warn');476 this.info = this.sandbox.stub(log, 'info');477 this.printAvailableNetworks = this.sandbox.stub(controller, 'printAvailableNetworks').returns(Promise.resolve());478 this.connectToNetwork = this.sandbox.stub(controller, 'connectToNetwork').returns(Promise.resolve());479 this.getWifiInfo = this.sandbox.stub(controller, 'getWifiInfo').returns(Promise.resolve());480 this.successfulCommand = this.sandbox.stub(t2, 'closeSuccessfulCommand');481 this.failedCommand = this.sandbox.stub(t2, 'closeFailedCommand');482 done();483 },484 tearDown(done) {485 this.sandbox.restore();486 done();487 },488 noOpts(test) {489 test.expect(3);490 t2(['wifi']);491 // We should not call either of these functions if no args were passed492 test.equal(this.printAvailableNetworks.callCount, 0);493 test.equal(this.connectToNetwork.callCount, 0);494 // It should call the getWiFiInfo function495 test.equal(this.getWifiInfo.callCount, 1);496 test.done();497 },498 listNoError(test) {499 test.expect(1);500 var resolve = Promise.resolve();501 this.printAvailableNetworks.returns(resolve);502 t2(['wifi', '--list']);503 resolve.then(() => {504 test.equal(this.successfulCommand.callCount, 1);505 test.done();506 });507 },508 offNoError(test) {509 test.expect(2);510 var resolve = Promise.resolve();511 this.printAvailableNetworks.returns(resolve);512 this.setWiFiState = this.sandbox.stub(controller, 'setWiFiState').returns(Promise.resolve());513 t2(['wifi', '--off']);514 resolve.then(() => {515 test.equal(this.setWiFiState.callCount, 1);516 test.equal(this.successfulCommand.callCount, 1);517 test.done();518 });519 },520 onNoError(test) {521 test.expect(2);522 var resolve = Promise.resolve();523 this.printAvailableNetworks.returns(resolve);524 this.setWiFiState = this.sandbox.stub(controller, 'setWiFiState').returns(Promise.resolve());525 t2(['wifi', '--on']);526 resolve.then(() => {527 test.equal(this.setWiFiState.callCount, 1);528 test.equal(this.successfulCommand.callCount, 1);529 test.done();530 });531 },532 listErrorExitCodeOne(test) {533 test.expect(1);534 var reject = Promise.reject();535 this.printAvailableNetworks.returns(reject);536 t2(['wifi', '--list']);537 reject.catch(() => {538 throw 'Without this, the catch in the test is invoked before the catch in the cli program.';539 }).catch(() => {540 test.equal(this.failedCommand.callCount, 1);541 test.done();542 });543 },544 ssidPassNoError(test) {545 test.expect(1);546 var resolve = Promise.resolve();547 this.connectToNetwork.returns(resolve);548 t2(['wifi', '--ssid', 'a', '--password', 'b']);549 resolve.then(() => {550 test.equal(this.successfulCommand.callCount, 1);551 test.done();552 });553 },554 ssidPassErrorExitCodeOne(test) {555 test.expect(1);556 var reject = Promise.reject();557 this.connectToNetwork.returns(reject);558 t2(['wifi', '--ssid', 'a', '--password', 'b']);559 reject.catch(() => {560 throw 'Without this, the catch in the test is invoked before the catch in the cli program.';561 }).catch(() => {562 test.equal(this.failedCommand.callCount, 1);563 test.done();564 });565 },566};567exports['Tessel (t2: root)'] = {568 setUp(done) {569 this.sandbox = sinon.sandbox.create();570 this.spinnerStart = this.sandbox.stub(log.spinner, 'start');571 this.spinnerStop = this.sandbox.stub(log.spinner, 'stop');572 this.warn = this.sandbox.stub(log, 'warn');573 this.info = this.sandbox.stub(log, 'info');574 this.root = this.sandbox.stub(controller, 'root').returns(Promise.resolve());575 this.successfulCommand = this.sandbox.stub(t2, 'closeSuccessfulCommand');576 done();577 },578 tearDown(done) {579 this.sandbox.restore();580 done();581 },582 callThrough(test) {583 test.expect(2);584 var resolve = Promise.resolve();585 this.root.returns(resolve);586 t2(['root']);587 resolve.then(() => {588 test.equal(this.root.callCount, 1);589 test.equal(this.successfulCommand.callCount, 1);590 test.done();591 });592 },593};594exports['Tessel (t2: run)'] = {595 setUp(done) {596 this.sandbox = sinon.sandbox.create();597 this.spinnerStart = this.sandbox.stub(log.spinner, 'start');598 this.spinnerStop = this.sandbox.stub(log.spinner, 'stop');599 this.warn = this.sandbox.stub(log, 'warn');600 this.info = this.sandbox.stub(log, 'info');601 this.deploy = this.sandbox.stub(controller, 'deploy').returns(Promise.resolve());602 this.successfulCommand = this.sandbox.stub(t2, 'closeSuccessfulCommand');603 done();604 },605 tearDown(done) {606 this.sandbox.restore();607 done();608 },609 defaultOptions(test) {610 test.expect(6);611 t2(['run', 'index.js']);612 test.equal(this.deploy.callCount, 1);613 var args = this.deploy.lastCall.args[0];614 // These represent the minimum required properties615 // and default values for `t2 run index.js`616 test.equal(args.slim, true);617 test.equal(args.lanPrefer, false);618 test.equal(args.full, false);619 test.equal(args.push, false);620 test.ok(!args.rustcc);621 setImmediate(test.done);622 },623 fullSetTrue_slimOverriddenLater(test) {624 test.expect(5);625 t2(['run', 'index.js', '--full=true']);626 test.equal(this.deploy.callCount, 1);627 var args = this.deploy.lastCall.args[0];628 // opts.full will override opts.slim in `tarBundle`629 // (See test/unit/deploy.js)630 test.equal(args.full, true);631 test.equal(args.slim, true);632 test.equal(args.lanPrefer, false);633 test.ok(!args.push);634 setImmediate(test.done);635 },636 binopts(test) {637 test.expect(3);638 t2(['run', 'index.js', '--binopts="--a"']);639 test.equal(this.deploy.callCount, 1);640 var args = this.deploy.lastCall.args[0];641 test.deepEqual(args.binopts, ['--a']);642 test.ok(!args.push);643 setImmediate(test.done);644 },645 binoptsList(test) {646 test.expect(3);647 t2(['run', 'index.js', '--binopts=--a,--b,--c']);648 test.equal(this.deploy.callCount, 1);649 var args = this.deploy.lastCall.args[0];650 test.deepEqual(args.binopts, ['--a', '--b', '--c']);651 test.ok(!args.push);652 setImmediate(test.done);653 },654};655exports['Tessel (t2: push)'] = {656 setUp(done) {657 this.sandbox = sinon.sandbox.create();658 this.spinnerStart = this.sandbox.stub(log.spinner, 'start');659 this.spinnerStop = this.sandbox.stub(log.spinner, 'stop');660 this.warn = this.sandbox.stub(log, 'warn');661 this.info = this.sandbox.stub(log, 'info');662 this.deploy = this.sandbox.stub(controller, 'deploy').returns(Promise.resolve());663 this.successfulCommand = this.sandbox.stub(t2, 'closeSuccessfulCommand');664 done();665 },666 tearDown(done) {667 this.sandbox.restore();668 done();669 },670 defaultOptions(test) {671 test.expect(6);672 t2(['push', 'index.js']);673 test.equal(this.deploy.callCount, 1);674 var args = this.deploy.lastCall.args[0];675 // These represent the minimum required properties676 // and default values for `t2 push index.js`677 test.ok(args.lanPrefer);678 test.ok(args.slim);679 test.ok(args.push);680 test.ok(!args.full);681 test.ok(!args.rustcc);682 setImmediate(test.done);683 },684 fullSetTrue_slimOverriddenLater(test) {685 test.expect(5);686 t2(['push', 'index.js', '--full=true']);687 test.equal(this.deploy.callCount, 1);688 var args = this.deploy.lastCall.args[0];689 // opts.full will override opts.slim in `tarBundle`690 // (See test/unit/deploy.js)691 test.ok(args.full);692 test.ok(args.lanPrefer);693 test.ok(args.push);694 test.ok(args.slim);695 setImmediate(test.done);696 },697 binopts(test) {698 test.expect(3);699 t2(['push', 'index.js', '--binopts="--a"']);700 test.equal(this.deploy.callCount, 1);701 var args = this.deploy.lastCall.args[0];702 test.deepEqual(args.binopts, ['--a']);703 test.ok(args.push);704 setImmediate(test.done);705 },706 binoptsList(test) {707 test.expect(3);708 t2(['push', 'index.js', '--binopts=--a,--b,--c']);709 test.equal(this.deploy.callCount, 1);710 var args = this.deploy.lastCall.args[0];711 test.deepEqual(args.binopts, ['--a', '--b', '--c']);712 test.ok(args.push);713 setImmediate(test.done);714 },715};716exports['Tessel (t2: list)'] = {717 setUp(done) {718 this.sandbox = sinon.sandbox.create();719 this.spinnerStart = this.sandbox.stub(log.spinner, 'start');720 this.spinnerStop = this.sandbox.stub(log.spinner, 'stop');721 this.warn = this.sandbox.stub(log, 'warn');722 this.info = this.sandbox.stub(log, 'info');723 this.controllerList = this.sandbox.spy(controller, 'listTessels');724 this.tesselList = this.sandbox.stub(Tessel, 'list').returns(Promise.resolve());725 this.setDefaultKey = this.sandbox.spy(provision, 'setDefaultKey');726 this.processExit = this.sandbox.stub(process, 'exit');727 this.closeSuccessful = this.sandbox.stub(t2, 'closeSuccessfulCommand');728 this.closeFailed = this.sandbox.stub(t2, 'closeFailedCommand');729 done();730 },731 tearDown(done) {732 this.sandbox.restore();733 done();734 },735 listStandard(test) {736 test.expect(4);737 t2(['list', '--timeout', '0.001']);738 setImmediate(() => {739 // Ensure controller list was called740 test.ok(this.controllerList.calledOnce);741 // Ensure it did not have a key option742 test.ok(this.controllerList.lastCall.args[0].key === undefined);743 // We should not try to set the keypath if not specifically requested744 test.ok(!this.setDefaultKey.called);745 // Tessel list should have been called afterwards746 test.ok(this.tesselList.called);747 test.done();748 });749 },750 listKey(test) {751 test.expect(4);752 var keyPath = './FAKE_KEY';753 t2(['list', '--timeout', '0.001', '-i', keyPath]);754 setImmediate(() => {755 // Restore our func so other tests pass756 // Ensure list was called757 test.ok(this.controllerList.calledOnce);758 // It was called with the keypath759 test.ok(this.controllerList.lastCall.args[0].key === keyPath);760 // We did try to set the key path761 test.ok(this.setDefaultKey.called);762 // It was called with the key path763 test.ok(this.setDefaultKey.lastCall.args[0] === keyPath);764 test.done();765 });766 }767};768exports['closeFailedCommand'] = {769 setUp(done) {770 this.sandbox = sinon.sandbox.create();771 this.spinnerStart = this.sandbox.stub(log.spinner, 'start');772 this.spinnerStop = this.sandbox.stub(log.spinner, 'stop');773 this.error = this.sandbox.stub(log, 'error');774 this.warn = this.sandbox.stub(log, 'warn');775 this.processExit = this.sandbox.stub(process, 'exit');776 done();777 },778 tearDown(done) {779 this.sandbox.restore();780 done();781 },782 warningJustAString(test) {783 test.expect(3);784 t2.closeFailedCommand('a string');785 test.equal(this.warn.callCount, 1);786 test.equal(this.warn.lastCall.args[0], 'a string');787 test.equal(this.processExit.callCount, 1);788 test.done();789 },790 errorIsAnErrorObject(test) {791 test.expect(3);792 var error = new Error('for real');793 t2.closeFailedCommand(error);794 test.equal(this.error.callCount, 1);795 test.equal(this.error.lastCall.args[0], error.toString());796 test.equal(this.processExit.callCount, 1);797 test.done();798 },799 errorCode(test) {800 test.expect(4);801 var error = new Error('for real');802 error.code = 'red';803 t2.closeFailedCommand(error);804 test.equal(this.error.callCount, 1);805 test.equal(this.error.lastCall.args[0], error.toString());806 test.equal(this.processExit.callCount, 1);807 test.equal(this.processExit.lastCall.args[0], 'red');808 test.done();809 },810 errorCodeInOptions(test) {811 test.expect(4);812 var error = new Error('for real');813 t2.closeFailedCommand(error, {814 code: 'red'815 });816 test.equal(this.error.callCount, 1);817 test.equal(this.error.lastCall.args[0], error.toString());818 test.equal(this.processExit.callCount, 1);819 test.equal(this.processExit.lastCall.args[0], 'red');820 test.done();821 },822};823exports['--output true/false'] = {824 setUp(done) {825 this.sandbox = sinon.sandbox.create();826 this.spinnerStart = this.sandbox.stub(log.spinner, 'start');827 this.spinnerStop = this.sandbox.stub(log.spinner, 'stop');828 // console.error is used by the underlying log.info/error/warn calls829 this.info = this.sandbox.stub(log, 'info');830 this.error = this.sandbox.stub(log, 'error');831 this.controllerList = this.sandbox.spy(controller, 'listTessels');832 this.tesselList = this.sandbox.stub(Tessel, 'list').callsFake(() => {833 // Simulating what actually happens in Tessel.list834 // without the complexity of mocking a seeker835 log.info('Searching for devices...');836 return Promise.reject('No devices found...');837 });838 this.outputHelper = this.sandbox.spy(controller, 'outputHelper');839 this.processExit = this.sandbox.stub(process, 'exit');840 this.closeSuccessful = this.sandbox.stub(t2, 'closeSuccessfulCommand');841 this.closeFailed = this.sandbox.stub(t2, 'closeFailedCommand');842 done();843 },844 tearDown(done) {845 this.sandbox.restore();846 done();847 },848 defaultOutputTrue(test) {849 test.expect(5);850 t2(['list', '--timeout', '0.001']);851 setImmediate(() => {852 // Ensure list was called853 test.ok(this.controllerList.calledOnce);854 // We did try to set the output855 test.ok(this.outputHelper.calledOnce);856 // It was called proper flag (default is true)857 test.ok(this.outputHelper.lastCall.args[0].output === true);858 // Ensure we called Tessel List859 test.ok(this.tesselList.calledOnce);860 // log was called once at the start to indicate we're searching861 test.equal(this.info.callCount, 1);862 test.done();863 });864 },865 outputFalse(test) {866 test.expect(5);867 t2(['list', '--timeout', '0.001', '--output=false']);868 setImmediate(() => {869 // Restore our func so other tests pass870 // Ensure list was called871 test.ok(this.controllerList.calledOnce);872 // We did try to set the output873 test.ok(this.outputHelper.calledOnce);874 // It was called proper flag (default is true)875 test.ok(this.outputHelper.lastCall.args[0].output === false);876 // Ensure we called Tessel List877 test.ok(this.tesselList.calledOnce);878 // log was never called because we disabled it879 test.equal(this.error.callCount, 0);880 test.done();881 });882 },883};884exports['Tessel (t2: crash-reporter)'] = {885 setUp(done) {886 this.sandbox = sinon.sandbox.create();887 this.spinnerStart = this.sandbox.stub(log.spinner, 'start');888 this.spinnerStop = this.sandbox.stub(log.spinner, 'stop');889 this.warn = this.sandbox.stub(log, 'warn');890 this.info = this.sandbox.stub(log, 'info');891 this.closeSuccessful = this.sandbox.stub(t2, 'closeSuccessfulCommand');892 this.closeFailed = this.sandbox.stub(t2, 'closeFailedCommand');893 this.crOn = this.sandbox.stub(CrashReporter, 'on').returns(Promise.resolve());894 this.crOff = this.sandbox.stub(CrashReporter, 'off').returns(Promise.resolve());895 this.crPost = this.sandbox.stub(CrashReporter, 'post').returns(Promise.resolve());896 this.crStatus = this.sandbox.stub(CrashReporter, 'status').returns(Promise.resolve());897 this.crSubmit = this.sandbox.stub(CrashReporter, 'submit').returns(Promise.resolve());898 this.crTest = this.sandbox.stub(CrashReporter, 'test').returns(Promise.resolve());899 done();900 },901 tearDown(done) {902 this.sandbox.restore();903 done();904 },905 callThroughNoOptions(test) {906 test.expect(4);907 var resolve = Promise.resolve();908 this.crStatus.restore();909 this.crStatus = this.sandbox.stub(CrashReporter, 'status').returns(resolve);910 t2(['crash-reporter']);911 test.equal(this.crOn.callCount, 0);912 test.equal(this.crOff.callCount, 0);913 test.equal(this.crTest.callCount, 0);914 resolve.then(() => {915 test.equal(this.crStatus.callCount, 1);916 test.done();917 });918 },919 on(test) {920 test.expect(4);921 t2(['crash-reporter', '--on=true']);922 test.equal(this.crOn.callCount, 1);923 test.equal(this.crOff.callCount, 0);924 test.equal(this.crTest.callCount, 0);925 test.equal(this.crStatus.callCount, 0);926 test.done();927 },928 off(test) {929 test.expect(4);930 t2(['crash-reporter', '--off=true']);931 test.equal(this.crOn.callCount, 0);932 test.equal(this.crOff.callCount, 1);933 test.equal(this.crTest.callCount, 0);934 test.equal(this.crStatus.callCount, 0);935 test.done();936 },937 test(test) {938 test.expect(4);939 var resolve = Promise.resolve();940 this.crTest.restore();941 this.crTest = this.sandbox.stub(CrashReporter, 'test').returns(resolve);942 t2(['crash-reporter', '--test=true']);943 test.equal(this.crOn.callCount, 0);944 test.equal(this.crOff.callCount, 0);945 test.equal(this.crStatus.callCount, 0);946 resolve.then(() => {947 test.equal(this.crTest.callCount, 1);948 test.done();949 });950 },951 onAndTest(test) {952 test.expect(4);953 var resolve = Promise.resolve();954 this.crOn.restore();955 this.crOn = this.sandbox.stub(CrashReporter, 'on').returns(resolve);956 t2(['crash-reporter', '--on', '--test']);957 resolve.then(() => {958 test.equal(this.crOn.callCount, 1);959 test.equal(this.crOff.callCount, 0);960 test.equal(this.crTest.callCount, 1);961 test.equal(this.crStatus.callCount, 0);962 test.done();963 });964 },965 onNoTestThrough(test) {966 test.expect(4);967 var resolve = Promise.resolve();968 this.crOn.restore();969 this.crOn = this.sandbox.stub(CrashReporter, 'on').returns(resolve);970 t2(['crash-reporter', '--on']);971 resolve.then(() => {972 test.equal(this.crOn.callCount, 1);973 test.equal(this.crOff.callCount, 0);974 test.equal(this.crTest.callCount, 0);975 test.equal(this.crStatus.callCount, 1);976 test.done();977 });978 },979 unsuccessful(test) {980 test.expect(4);981 var resolve = Promise.resolve();982 this.crOn.restore();983 this.crOn = this.sandbox.stub(CrashReporter, 'on').returns(resolve);984 t2(['crash-reporter', '--on']);985 resolve.then(() => {986 test.equal(this.crOn.callCount, 1);987 test.equal(this.crOff.callCount, 0);988 test.equal(this.crTest.callCount, 0);989 test.equal(this.crStatus.callCount, 1);990 test.done();991 });992 },993};994exports['Tessel (init)'] = {995 setUp(done) {996 this.sandbox = sinon.sandbox.create();997 this.warn = this.sandbox.stub(log, 'warn');998 this.info = this.sandbox.stub(log, 'info');999 this.successfulCommand = this.sandbox.stub(t2, 'closeSuccessfulCommand');1000 this.failedCommand = this.sandbox.stub(t2, 'closeFailedCommand');1001 this.resolveLanguage = this.sandbox.spy(init, 'resolveLanguage');1002 done();1003 },1004 tearDown(done) {1005 this.sandbox.restore();1006 done();1007 },1008 'defaults to --lang=js' (test) {1009 test.expect(3);1010 var resolve = Promise.resolve();1011 this.createNewProject = this.sandbox.stub(controller, 'createNewProject').returns(resolve);1012 t2(['init']);1013 resolve.then(() => {1014 // Infers that the stub above called and not the actual createNewProject1015 test.equal(this.resolveLanguage.callCount, 0);1016 test.equal(this.createNewProject.callCount, 1);1017 test.equal(this.createNewProject.lastCall.args[0].lang, 'js');1018 test.done();1019 });1020 },1021 'explicit --lang=js' (test) {1022 test.expect(3);1023 var resolve = Promise.resolve();1024 this.createNewProject = this.sandbox.stub(controller, 'createNewProject').returns(resolve);1025 t2(['init', '--lang=js']);1026 resolve.then(() => {1027 // Infers that the stub above called and not the actual createNewProject1028 test.equal(this.resolveLanguage.callCount, 0);1029 test.equal(this.createNewProject.callCount, 1);1030 test.equal(this.createNewProject.lastCall.args[0].lang, 'js');1031 test.done();1032 });1033 },1034 'explicit --lang=javascript' (test) {1035 test.expect(3);1036 var resolve = Promise.resolve();1037 this.createNewProject = this.sandbox.stub(controller, 'createNewProject').returns(resolve);1038 t2(['init', '--lang=javascript']);1039 resolve.then(() => {1040 // Infers that the stub above called and not the actual createNewProject1041 test.equal(this.resolveLanguage.callCount, 0);1042 test.equal(this.createNewProject.callCount, 1);1043 test.equal(this.createNewProject.lastCall.args[0].lang, 'javascript');1044 test.done();1045 });1046 },1047 'explicit --lang=rs' (test) {1048 test.expect(3);1049 var resolve = Promise.resolve();1050 this.createNewProject = this.sandbox.stub(controller, 'createNewProject').returns(resolve);1051 t2(['init', '--lang=rs']);1052 resolve.then(() => {1053 // Infers that the stub above called and not the actual createNewProject1054 test.equal(this.resolveLanguage.callCount, 0);1055 test.equal(this.createNewProject.callCount, 1);1056 test.equal(this.createNewProject.lastCall.args[0].lang, 'rs');1057 test.done();1058 });1059 },1060 'explicit --lang=rust' (test) {1061 test.expect(3);1062 var resolve = Promise.resolve();1063 this.createNewProject = this.sandbox.stub(controller, 'createNewProject').returns(resolve);1064 t2(['init', '--lang=rust']);1065 resolve.then(() => {1066 // Infers that the stub above called and not the actual createNewProject1067 test.equal(this.resolveLanguage.callCount, 0);1068 test.equal(this.createNewProject.callCount, 1);1069 test.equal(this.createNewProject.lastCall.args[0].lang, 'rust');1070 test.done();1071 });1072 },1073};1074exports['Tessel (t2: installer-*)'] = {1075 setUp(done) {1076 this.sandbox = sinon.sandbox.create();1077 this.spinnerStart = this.sandbox.stub(log.spinner, 'start');1078 this.spinnerStop = this.sandbox.stub(log.spinner, 'stop');1079 this.warn = this.sandbox.stub(log, 'warn');1080 this.info = this.sandbox.stub(log, 'info');1081 this.closeSuccessful = this.sandbox.stub(t2, 'closeSuccessfulCommand');1082 this.closeFailed = this.sandbox.stub(t2, 'closeFailedCommand');1083 this.drivers = this.sandbox.stub(installer, 'drivers').returns(Promise.resolve());1084 this.homedir = this.sandbox.stub(installer, 'homedir').returns(Promise.resolve());1085 done();1086 },1087 tearDown(done) {1088 this.sandbox.restore();1089 done();1090 },1091 npmScriptPostinstall(test) {1092 test.expect(1);1093 test.equal(1094 cliPackageJson.scripts.postinstall,1095 't2 install drivers --loglevel=error || true; t2 install homedir --loglevel=error || true;'1096 );1097 test.done();1098 },1099 callThroughNoOptions(test) {1100 test.expect(8);1101 var dresolve = Promise.resolve();1102 var hresolve = Promise.resolve();1103 this.drivers.restore();1104 this.homedir.restore();1105 this.drivers = this.sandbox.stub(installer, 'drivers').returns(dresolve);1106 this.homedir = this.sandbox.stub(installer, 'homedir').returns(hresolve);1107 t2(['install', 'drivers']);1108 t2(['install', 'homedir']);1109 test.equal(this.drivers.callCount, 1);1110 test.equal(this.homedir.callCount, 1);1111 Promise.all([dresolve, hresolve]).then(() => {1112 test.equal(this.drivers.callCount, 1);1113 test.equal(this.homedir.callCount, 1);1114 test.equal(this.drivers.lastCall.args[0][0], 'install');1115 test.equal(this.homedir.lastCall.args[0][0], 'install');1116 test.equal(this.drivers.lastCall.args[0].operation, 'drivers');1117 test.equal(this.homedir.lastCall.args[0].operation, 'homedir');1118 test.done();1119 });1120 },1121};1122exports['Tessel (t2: [subargs])'] = {1123 setUp(done) {1124 this.sandbox = sinon.sandbox.create();1125 this.parse = this.sandbox.stub(t2.nomnom, 'parse');1126 done();1127 },1128 tearDown(done) {1129 this.sandbox.restore();1130 t2.nomnom.subargs = undefined;1131 done();1132 },1133 emptyNoWhitespace(test) {1134 test.expect(3);1135 // t2 run foo.js []1136 t2(['run', 'foo.js', '[]']);1137 test.equal(this.parse.callCount, 1);1138 test.deepEqual(this.parse.lastCall.args[0], ['run', 'foo.js']);1139 test.deepEqual(t2.nomnom.subargs, []);1140 test.done();1141 },1142 emptyWithWhitespace(test) {1143 test.expect(3);1144 // t2 run foo.js [ ]1145 t2(['run', 'foo.js', '[ ]']);1146 test.equal(this.parse.callCount, 1);1147 test.deepEqual(this.parse.lastCall.args[0], ['run', 'foo.js']);1148 test.deepEqual(t2.nomnom.subargs, []);1149 test.done();1150 },1151 emptySingleNoWhitespace(test) {1152 test.expect(3);1153 // t2 run foo.js [0]1154 t2(['run', 'foo.js', '[0]']);1155 test.equal(this.parse.callCount, 1);1156 test.deepEqual(this.parse.lastCall.args[0], ['run', 'foo.js']);1157 test.deepEqual(t2.nomnom.subargs, ['0']);1158 test.done();1159 },1160 emptySingleWithWhitespace(test) {1161 test.expect(3);1162 // t2 run foo.js [0 ]1163 t2(['run', 'foo.js', '[0', ']']);1164 test.equal(this.parse.callCount, 1);1165 test.deepEqual(this.parse.lastCall.args[0], ['run', 'foo.js']);1166 test.deepEqual(t2.nomnom.subargs, ['0']);1167 test.done();1168 },1169 emptyMultipleWithWhitespace(test) {1170 test.expect(3);1171 // t2 run foo.js [0 0 0 0]1172 t2(['run', 'foo.js', '[0', '0', '0', '0]']);1173 test.equal(this.parse.callCount, 1);1174 test.deepEqual(this.parse.lastCall.args[0], ['run', 'foo.js']);1175 test.deepEqual(t2.nomnom.subargs, ['0', '0', '0', '0']);1176 test.done();1177 },1178 emptyMultipleMixed(test) {1179 test.expect(3);1180 // t2 run foo.js [--foo=bar 0 x y z --a true 1 2 3 ]1181 t2(['run', 'foo.js', '[--foo=bar', '0', 'x', 'y', 'z', '--a', 'true', '1', '2', '3', ']']);1182 test.equal(this.parse.callCount, 1);1183 test.deepEqual(this.parse.lastCall.args[0], ['run', 'foo.js']);1184 test.deepEqual(1185 t2.nomnom.subargs, ['--foo=bar', '0', 'x', 'y', 'z', '--a', 'true', '1', '2', '3']1186 );1187 test.done();1188 },...

Full Screen

Full Screen

wifi.js

Source:wifi.js Github

copy

Full Screen

1'use strict';2// System Objects3// ...4// Third Party Dependencies5// ...6// Internal7var commands = require('./commands');8var log = require('../log');9var Tessel = require('./tessel');10Tessel.prototype.findAvailableNetworks = function() {11 var listed = {};12 return this.simpleExec(commands.scanWiFi())13 .then(function wifiScanResults(result) {14 // For each string chunk15 return result.trim().split('\n\n').reduce((networks, entry) => {16 try {17 var ssidRegex = /ESSID: "(.*)"/;18 var qualityRegex = /Quality: (.*)/;19 var encryptionRegex = /Encryption: (.*)/;20 var networkInfo = {21 // Parse out the SSID22 ssid: ssidRegex.exec(entry)[1],23 // Parse out the quality of the connection24 quality: qualityRegex.exec(entry)[1],25 // Parse the security type - unused at the moment26 security: encryptionRegex.exec(entry)[1],27 };28 if (!listed[networkInfo.ssid]) {29 listed[networkInfo.ssid] = true;30 // Add this parsed network to our array31 networks.push(networkInfo);32 }33 } catch (err) {34 // Suppress errors created by entries that cannot be parsed.35 }36 return networks;37 }, []).sort(compareBySignal);38 })39 .catch(function checkNoSuchDeviceError(err) {40 if (/No such wireless device/.test(err.message)) {41 return Promise.reject(new Error('Unable to find wireless networks while wifi is disabled. Run "t2 wifi --on" before trying again.'));42 }43 return Promise.reject(err);44 });45};46Tessel.prototype.getWifiInfo = function() {47 return this.simpleExec(commands.getWifiInfo())48 .then((resultsJSON) => {49 try {50 var network = JSON.parse(resultsJSON);51 if (network.ssid === undefined) {52 var msg = `${this.displayName} is not connected to Wi-Fi (run "t2 wifi -l" to see available networks)`;53 return Promise.reject(msg);54 }55 } catch (err) {56 return Promise.reject(err);57 }58 return this.simpleExec(commands.getIPAddress())59 .then(function(ipResults) {60 network.ips = ipResults.split('\n');61 return Promise.resolve(network);62 });63 })64 .catch((err) => {65 if (err.toString().includes('Not found')) {66 var msg = `${this.displayName} is not connected to Wi-Fi (run "t2 wifi -l" to see available networks)`;67 return Promise.reject(msg);68 } else {69 return Promise.reject(err);70 }71 });72};73function safeQualityExprEvaluation(expr) {74 const parsed = /(\d.*)(?:\/)(\d.*)/.exec(expr);75 const nexpr = +expr;76 const isNumber = parsed === null && typeof nexpr === 'number' && !Number.isNaN(nexpr);77 // If the expression doesn't match "\d.*/\d.*",78 // but IS a number, then return the number. Otherwise,79 // evaluate the expression as division. ToNumber is80 // applied implicitly. If the expression didn't parse81 // safely, return 0.82 return isNumber ? nexpr : (parsed && parsed.length === 3 ? parsed[1] / parsed[2] : 0);83}84function compareBySignal(a, b) {85 const ae = safeQualityExprEvaluation(a.quality);86 const be = safeQualityExprEvaluation(b.quality);87 if (ae > be) {88 return -1;89 } else if (ae < be) {90 return 1;91 } else {92 return 0;93 }94}95Tessel.prototype.connectToNetwork = function(options) {96 const ssid = options.ssid;97 const password = options.password;98 let security = options.security;99 let enable = true;100 if (password && !security) {101 security = 'psk2';102 }103 let configured = 'Wifi Configured.';104 let configuration = `SSID: ${ssid}`;105 if (password && security) {106 let passToDisplay;107 if (options.showpassword) {108 passToDisplay = password;109 } else {110 let rpass = /(^[a-z0-9])(.*?)([a-z0-9])$/ig;111 passToDisplay = password.replace(rpass, (w, f, m, l) => `${f}${'*'.repeat(m.length)}${l}`);112 }113 configuration += `, password: ${passToDisplay}, security: ${security}`;114 }115 if (!password && !security) {116 security = 'none';117 }118 const setSSID = () => {119 let resolution = Promise.resolve();120 if (password) {121 resolution = this.simpleExec(commands.setNetworkPassword(password));122 }123 return resolution.then(124 () => this.simpleExec(commands.setNetworkSSID(ssid))125 );126 };127 const setNetworkSecurity = () => this.simpleExec(commands.setNetworkEncryption(security));128 const turnWifiOn = () => this.setWiFiState({129 enable130 });131 return setSSID()132 .then(setNetworkSecurity)133 .then(turnWifiOn)134 .then(() => {135 log.info(`${configured} (${configuration})`);136 log.info(`Wifi Connected.`);137 });138};139Tessel.prototype.resetMDNS = function() {140 return this.simpleExec(commands.callMDNSDaemon('restart'))141 .then(() => this.simpleExec(commands.callTesselMDNS('restart')));142};143Tessel.prototype.setWiFiState = function(state) {144 if (!state) {145 return Promise.reject(new Error('Missing Wifi State: (empty).'));146 }147 if (typeof state.enable === 'undefined') {148 return Promise.reject(new Error('Missing Wifi State: property "enable" not provided.'));149 }150 return new Promise((resolve, reject) => {151 return this.simpleExec(commands.turnOnWifi(state.enable))152 .then(() => this.simpleExec(commands.commitWirelessCredentials()))153 .then(() => {154 return this.simpleExec(commands.reconnectWifi())155 .then((result) => {156 // check if the actual wifi radio (wireless.radio0) is disabled157 if (result.includes("'radio0' is disabled")) {158 return this.simpleExec(commands.turnRadioOn())159 .then(() => this.simpleExec(commands.commitWirelessCredentials()))160 .then(() => this.simpleExec(commands.reconnectWifi()))161 .catch(reject);162 }163 });164 })165 .then(() => {166 const enabledOrDisabled = state.enable ? 'Enabled' : 'Disabled';167 const settle = (rejection) => {168 if (rejection) {169 reject(rejection);170 } else {171 log.info(`Wifi ${enabledOrDisabled}.`);172 resolve();173 }174 };175 /*176 To explain the following "magic number"...177 The `tries` limit is set to 10 as an arbitrarily chosen minimum and maximum restriction.178 This could actually be increased to ~33, which is the approximate number of tries179 that could potentially be made in 12 seconds (the delay period (2) + timeout period (10)).180 This was determined by counting the number of complete tries made against a181 known invalid ssid, within a 12 second period. I ran the measurement code 10 times182 and the rounded average count was 33 tries.183 `tries` shouldn't be set lower than 10, as each wifi info request takes approximately 340ms.184 This was determined by measuring the time between each attempt against a known invalid185 ssid (with no tries limit). 340 is the rounded average of 10 complete operations, including186 only the lowest number of measurements; ie. if one operation made 35 tries, and nine187 operatons made 30 tries, then the only the first 30 were included in the result set.188 The result is a maximum of 3.4s before verification is treated as a failure.189 This is slightly more than the previous delay + one operation, but substantially less than190 the full 10 second timeout, with a higher likelihood of success (that is, zero failures were191 observed when using a valid ssid + password + security).192 */193 let tries = 10;194 const pollForWifiSignal = () => {195 this.connection.exec(commands.getWifiInfo(), (error, remoteProcess) => {196 if (error) {197 return reject(error);198 }199 this.receive(remoteProcess, (error, result) => {200 if (error) {201 if (error.toString().includes('Not found') && tries) {202 tries--;203 return pollForWifiSignal();204 } else {205 return reject(error);206 }207 }208 if (result.toString().includes('signal')) {209 settle();210 } else {211 tries--;212 if (tries) {213 pollForWifiSignal();214 } else {215 settle('Unable to verify connection. Please ensure you have entered the correct network credentials.');216 }217 }218 });219 });220 };221 if (state.enable) {222 pollForWifiSignal();223 } else {224 settle();225 }226 });227 });...

Full Screen

Full Screen

api-store.js

Source:api-store.js Github

copy

Full Screen

1import {2 observable,3 computed,4 action,5 configure,6 runInAction7} from 'mobx';8import ApiSocket from '../components/api-socket';9configure({10 enforceActions: 'observed',11 isolateGlobalState: true,12 disableErrorBoundaries: false13});14const api = new ApiSocket();15export default class ApiStore {16 @observable _receiverState = {17 enabled: false,18 timeStart: 0,19 timeReceive: 0,20 writeToSd: true,21 sendToTcp: true22 };23 @observable _ntripState = {24 enabled: false,25 timeStart: 0,26 timeReceive: 0,27 host: '',28 port: '',29 mountPoint: '',30 lastUpdate: null31 };32 @observable _serverState = {33 serverStart: 0,34 sdSuccess: false35 };36 @observable _wifiState = {37 list: [],38 lastUpdate: null,39 wifiMode: api.WiFiModes.unknown,40 apInfo: null,41 staInfo: null42 };43 @action44 setReceiverState(state) {45 if (typeof state == 'function') {46 state = state(this._receiverState);47 }48 this._receiverState = {49 ...this._receiverState,50 ...state51 };52 }53 @action54 setNtripState(state) {55 if (typeof state == 'function') {56 state = state(this._ntripState);57 }58 this._ntripState = {59 ...this._ntripState,60 ...state61 };62 }63 @computed64 get ntripState() {65 return this._ntripState;66 }67 @action68 async updateNtripState() {69 if (70 this._ntripState &&71 this._ntripState.lastUpdate &&72 new Date() - this._ntripState.lastUpdate < 50073 ) {74 return this.sendApiWarn('Small time interval');75 }76 try {77 const res = await api.getNtripState();78 console.debug({ res });79 if (res && res.data) {80 runInAction(() => {81 this._ntripState.enabled = res.data.enabled;82 });83 return null;84 }85 } catch (err) {86 return this.sendApiError(err, api.components.ntrip);87 }88 }89 @action90 async ntripAction(enable, options) {91 try {92 const res = await api.setNtripClient(enable, options);93 if (res && res.data) {94 runInAction(() => {95 this.setNtripState(res.data);96 });97 return res;98 }99 } catch (err) {100 return this.sendApiError(err, api.components.ntrip);101 }102 return null;103 }104 @action105 setServerState(state) {106 if (typeof state == 'function') {107 state = state(this._serverState);108 }109 this._serverState = {110 ...this._serverState,111 ...state112 };113 }114 @action115 setWiFiState(state) {116 if (typeof state == 'function') {117 state = state(this._wifiState);118 }119 this._wifiState = {120 ...this._wifiState,121 ...state122 };123 }124 @computed125 get receiverState() {126 return this._receiverState;127 }128 @computed129 get serverState() {130 return this._serverState;131 }132 @computed133 get wifiState() {134 return this._wifiState;135 }136 @computed137 get timeReceive() {138 const { enabled, timeStart } = this._receiverState;139 const { serverStart } = this.serverState;140 //console.log({enabled, timeStart, serverStart})141 if (!enabled || !timeStart) {142 return 0;143 }144 return Date.now() - timeStart - serverStart;145 }146 @computed147 get serverStartTime() {148 return new Date(Date.now() - this._serverState.serverStart);149 }150 @action151 async updateServerState() {152 try {153 const res = await api.getServerInfo();154 runInAction(() => {155 this._serverState.serverStart =156 Date.now() - res.data.serverTime;157 this._serverState.sdSuccess = res.data.sdSuccess;158 });159 return null;160 } catch (err) {161 return this.sendApiError(err, api.components.server);162 }163 }164 @action165 async updateReceiverState() {166 try {167 if (168 this._receiverState &&169 this._receiverState.lastUpdate &&170 new Date() - this._receiverState.lastUpdate < 1000171 ) {172 return this.sendApiWarn('Small time interval');173 }174 const res = await api.getReceiverState();175 const {176 enabled,177 timeStart,178 timeReceive,179 writeToSd,180 sendToTcp181 } = res.data;182 //this._receiverState = {183 // enabled,184 // timeStart,185 // timeReceive186 //};187 runInAction(() => {188 this.setReceiverState({189 enabled,190 timeStart,191 timeReceive,192 writeToSd,193 sendToTcp,194 lastUpdate: new Date()195 });196 });197 return null;198 } catch (err) {199 return this.sendApiError(err, api.components.receiver);200 }201 }202 @action203 async updateWiFiList() {204 try {205 if (206 this._wifiState &&207 this._wifiState.lastUpdate &&208 new Date() - this._wifiState.lastUpdate < 1000209 ) {210 return this.sendApiWarn('Small time interval');211 }212 const res = await api.getWifiList();213 //this._wifiState.list = res.data;214 //this._wifiState.lastUpdate = new Date();215 runInAction(() => {216 this.setWiFiState({217 list: res.data,218 lastUpdate: new Date()219 });220 });221 return null;222 } catch (err) {223 return this.sendApiError(err, api.components.wifi);224 }225 }226 @action227 async updateWiFiInfo() {228 try {229 const res = await api.getWifiInfo();230 runInAction(() => {231 this.setWiFiState({232 wifiMode: res.data.mode || api.WiFiModes.unknown,233 apInfo: res.data.ap || null,234 staInfo: res.data.sta || null235 });236 });237 return null;238 } catch (err) {239 return this.sendApiError(err, api.components.wifi);240 }241 }242 sendApiError = (err, component) => {243 console.error(`Error {ApiStore}, Component: [${component}]`, {244 err,245 sender: this246 });247 return err;248 };249 sendApiWarn = (warn, component) => {250 console.warn('Warn {ApiStore}, Component: [${component}]', {251 warn,252 sender: this253 });254 return warn;255 };256 get api() {257 return api;258 }...

Full Screen

Full Screen

network.js

Source:network.js Github

copy

Full Screen

...37 await this.adb.broadcastAirplaneMode(airplaneMode);38 });39 if (!airplaneMode) {40 await this.wrapBootstrapDisconnect(async () => {41 await this.setWifiState(wifi);42 await this.adb.setDataState(data, this.isEmulator());43 });44 }45 return await this.getNetworkConnection();46};47/**48 * decoupling to override behaviour in other drivers like UiAutomator2.49 */50commands.setWifiState = async function (wifi) {51 await this.adb.setWifiState(wifi, this.isEmulator());52};53commands.toggleData = async function () {54 let data = !(await this.adb.isDataOn());55 log.info(`Turning network data ${data ? 'on' : 'off'}`);...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1 withCapabilities({2 build();3driver.setWifiState(false).then(function () {4 console.log("Wifi state set to false");5 return driver.setWifiState(true);6}).then(function () {7 console.log("Wifi state set to true");8}).fin(function () {9 return driver.quit();10}).done();11 withCapabilities({12 build();13driver.setNetworkConnection(6).then(function () {14 console.log("Network connection set to 6");15 return driver.setNetworkConnection(2);16}).then(function () {17 console.log("Network connection set to 2");18}).fin(function () {19 return driver.quit();20}).done();21 withCapabilities({22 build();23driver.getNetworkConnection().then(function (connection) {24 console.log("Network connection type: " + connection);25}).fin(function () {26 return driver.quit();27}).done();

Full Screen

Using AI Code Generation

copy

Full Screen

1var webdriver = require('selenium-webdriver');2 build();3driver.manage().window().maximize();4driver.quit();5driver.getWifiState(function (err, state) {6});7driver.getGpsState(function (err, state) {8});9driver.getBluetoothState(function (err, state) {10});11driver.getWifiState(function (err, state) {12});13driver.getGpsState(function (err, state) {14});15driver.getBluetoothState(function (err, state) {16});17driver.getWifiState(function (err, state) {18});19driver.getGpsState(function (err, state) {20});21driver.getBluetoothState(function (err, state) {22});23driver.getWifiState(function (err, state) {24});25driver.getGpsState(function (err, state) {26});27driver.getBluetoothState(function (err, state) {28});29driver.getWifiState(function (err, state) {30});31driver.getGpsState(function (err, state) {

Full Screen

Using AI Code Generation

copy

Full Screen

1var webdriver = require('selenium-webdriver');2var driver = new webdriver.Builder().forBrowser('chrome').build();3driver.getTitle().then(function(title) {4 console.log('Title is: ' + title);5});6driver.quit();7var webdriver = require('selenium-webdriver');8var driver = new webdriver.Builder().forBrowser('chrome').build();9driver.getTitle().then(function(title) {10 console.log('Title is: ' + title);11});12driver.quit();13var webdriver = require('selenium-webdriver');14var driver = new webdriver.Builder().forBrowser('chrome').build();15driver.getTitle().then(function(title) {16 console.log('Title is: ' + title);17});18driver.quit();19var webdriver = require('selenium-webdriver');20var driver = new webdriver.Builder().forBrowser('chrome').build();21driver.getTitle().then(function(title) {22 console.log('Title is: ' + title);23});24driver.quit();25var webdriver = require('selenium-webdriver');26var driver = new webdriver.Builder().forBrowser('chrome').build();27driver.getTitle().then(function(title) {28 console.log('Title is: ' + title);29});30driver.quit();31var webdriver = require('selenium-webdriver');32var driver = new webdriver.Builder().forBrowser('chrome').build();33driver.getTitle().then(function(title) {34 console.log('Title is: ' + title);35});36driver.quit();37var webdriver = require('selenium-webdriver');38var driver = new webdriver.Builder().forBrowser('chrome').build();39driver.getTitle().then(function(title) {40 console.log('Title is: ' + title);41});42driver.quit();

Full Screen

Using AI Code Generation

copy

Full Screen

1var webdriver = require('selenium-webdriver');2var appium = require('appium');3var assert = require('assert');4withCapabilities({5}).build();6driver.setWifiState(true);7driver.quit();8Your name to display (optional):9Your name to display (optional):10driver.setWifiState(true);11driver.setWifiState(false);12Your name to display (optional):

Full Screen

Using AI Code Generation

copy

Full Screen

1driver.setWifiState(true).then(function () {2});3driver.setWifiState(false).then(function () {4});5driver.setWifiState(1).then(function () {6});7driver.setWifiState(0).then(function () {8});9driver.setWifiState("true").then(function () {10});11driver.setWifiState("false").then(function () {12});13driver.setWifiState("1").then(function () {14});15driver.setWifiState("0").then(function () {16});17driver.setWifiState("True").then(function () {18});19driver.setWifiState("False").then(function () {20});21driver.setWifiState("On").then(function () {22});23driver.setWifiState("Off").then(function () {24});25driver.setWifiState("on").then(function () {26});27driver.setWifiState("off").then(function () {28});29driver.setWifiState("ON").then(function ()

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Appium Android Driver automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful