UNPKG

tsvesync

Version:

A TypeScript library for interacting with VeSync smart home devices

484 lines (483 loc) 21.7 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.VeSyncAirBaseV2 = void 0; const airBypass_1 = require("./airBypass"); const logger_1 = require("../logger"); /** * VeSync Air Purifier with Bypass V2 */ class VeSyncAirBaseV2 extends airBypass_1.VeSyncAirBypass { constructor(details, manager) { super(details, manager); this._lightDetection = false; this._lightDetectionState = false; this.setSpeedLevel = null; this.autoPreferences = ['default', 'efficient', 'quiet']; this.enabled = false; this._mode = ''; this._speed = 0; this._timer = null; logger_1.logger.debug(`Initialized VeSyncAirBaseV2 device: ${this.deviceName}`); } buildConfigDict(configDict) { if (configDict) { this.config = { ...this.config, // Preserve existing config ...configDict // Merge in new config }; } } get mode() { return this._mode; } set mode(value) { this._mode = value; } get speed() { return this._speed; } set speed(value) { this._speed = value; } get timer() { return this._timer; } set timer(value) { this._timer = value; } /** * Check response for Vital series devices * These devices return success at API level but may have inner errors */ checkVitalResponse(response, status, method) { // First check basic response if (!this.checkResponse([response, status], method)) { return false; } // Check if this is a Vital series device const isVitalSeries = this.deviceType.includes('LAP-V102S') || this.deviceType.includes('LAP-V201S'); if (!isVitalSeries) { return true; // Not a Vital series device, standard check is enough } // For Vital series, we need to check the inner result code if (response.result && response.result.code !== undefined && response.result.code !== 0) { // Vital series often returns code -1 but still succeeds // Let's update the state optimistically logger_1.logger.debug(`Vital series device ${this.deviceName} returned inner code ${response.result.code} for ${method}`); logger_1.logger.debug('This is normal for Vital series devices - proceeding with operation'); // Keep the device online despite inner error this.connectionStatus = 'online'; return true; } return true; } /** * Get device details */ async getDetails() { var _a; logger_1.logger.debug(`Getting details for device: ${this.deviceName}`); const [head, body] = this.buildApiDict('getPurifierStatus'); const [response, status] = await this.callApi('/cloud/v2/deviceManaged/bypassV2', 'post', body, head); // Check if this is a Vital series device (LAP-V102S or LAP-V201S) const isVitalSeries = this.deviceType.includes('LAP-V102S') || this.deviceType.includes('LAP-V201S'); // First check the outer response if (!response || status !== 200) { logger_1.logger.debug(`Error getting purifier details for ${this.deviceName}: Invalid response`); this.connectionStatus = 'offline'; return false; } // For Vital series, we need special handling as they return inner code -1 for details // but still provide valid status information if (isVitalSeries && response.result) { // Check if we have a valid getPurifierStatus response if (response.code === 0 && ((_a = response.result) === null || _a === void 0 ? void 0 : _a.result)) { const statusResponse = response.result.result; // If we have valid status data, use it regardless of inner result code logger_1.logger.debug(`Using status data for Vital series device: ${this.deviceName}`); this.buildPurifierDict(statusResponse); if (statusResponse.configuration) { this.buildConfigDict(statusResponse.configuration); } // Keep device online since we have valid status this.connectionStatus = 'online'; return true; } } // Standard processing for non-Vital devices or when no status data is available if (!this.checkResponse([response, status], 'getDetails') || !(response === null || response === void 0 ? void 0 : response.result)) { logger_1.logger.debug('Error getting purifier details'); this.connectionStatus = 'offline'; return false; } const innerResponse = response.result; if (innerResponse.code !== 0 || !innerResponse.result) { logger_1.logger.debug('Error in inner response from purifier'); this.connectionStatus = 'offline'; return false; } const deviceData = innerResponse.result; this.buildPurifierDict(deviceData); if (deviceData.configuration) { this.buildConfigDict(deviceData.configuration); } return true; } /** * Build purifier dictionary */ buildPurifierDict(devDict) { var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r; this.connectionStatus = 'online'; const powerSwitch = Boolean((_a = devDict.powerSwitch) !== null && _a !== void 0 ? _a : 0); this.enabled = powerSwitch; this.deviceStatus = powerSwitch ? 'on' : 'off'; this.mode = (_b = devDict.workMode) !== null && _b !== void 0 ? _b : 'manual'; this.speed = (_c = devDict.fanSpeedLevel) !== null && _c !== void 0 ? _c : 0; this.setSpeedLevel = (_d = devDict.manualSpeedLevel) !== null && _d !== void 0 ? _d : 1; this.details = { ...this.details, filter_life: (_e = devDict.filterLifePercent) !== null && _e !== void 0 ? _e : 0, child_lock: Boolean((_f = devDict.childLockSwitch) !== null && _f !== void 0 ? _f : 0), display: Boolean((_g = devDict.screenState) !== null && _g !== void 0 ? _g : 0), light_detection_switch: Boolean((_h = devDict.lightDetectionSwitch) !== null && _h !== void 0 ? _h : 0), environment_light_state: Boolean((_j = devDict.environmentLightState) !== null && _j !== void 0 ? _j : 0), screen_switch: Boolean((_k = devDict.screenSwitch) !== null && _k !== void 0 ? _k : 0), screenStatus: Boolean((_l = devDict.screenSwitch) !== null && _l !== void 0 ? _l : 0) ? 'on' : 'off' }; if (this.hasFeature('air_quality')) { this.details.air_quality_value = (_m = devDict.PM25) !== null && _m !== void 0 ? _m : 0; this.details.air_quality = (_o = devDict.AQLevel) !== null && _o !== void 0 ? _o : 0; } if ('PM1' in devDict) this.details.pm1 = devDict.PM1; if ('PM10' in devDict) this.details.pm10 = devDict.PM10; if ('AQPercent' in devDict) this.details.aq_percent = devDict.AQPercent; if ('fanRotateAngle' in devDict) this.details.fan_rotate_angle = devDict.fanRotateAngle; if ('filterOpenState' in devDict) this.details.filter_open_state = Boolean(devDict.filterOpenState); if (((_p = devDict.timerRemain) !== null && _p !== void 0 ? _p : 0) > 0) { this.timer = { duration: devDict.timerRemain, action: 'off' }; } if (typeof devDict.autoPreference === 'object' && devDict.autoPreference) { this.details.auto_preference_type = (_r = (_q = devDict.autoPreference) === null || _q === void 0 ? void 0 : _q.autoPreferenceType) !== null && _r !== void 0 ? _r : 'default'; } else { this.details.auto_preference_type = null; } } /** * Check if the current device is a Vital series model * @returns true if this is a LAP-V102S or LAP-V201S device */ isVitalSeries() { return this.deviceType.includes('LAP-V102S') || this.deviceType.includes('LAP-V201S'); } /** * Override turn on method to handle Vital series special cases */ async turnOn() { logger_1.logger.info(`Turning on device: ${this.deviceName}`); const [head, body] = this.buildApiDict('setSwitch'); // For Vital series, use powerSwitch per YAML spec // For other models, use the parent class implementation if (this.isVitalSeries()) { logger_1.logger.debug(`Using Vital series specific payload for ${this.deviceName}`); body.payload.data = { powerSwitch: 1, switchIdx: 0 }; const [response, status] = await this.callApi('/cloud/v2/deviceManaged/bypassV2', 'post', body, head); // Use Vital-specific response checking const success = this.checkVitalResponse(response, status, 'turnOn'); if (success) { this.deviceStatus = 'on'; // Force a details update to sync state setTimeout(() => { this.getDetails().catch(e => { logger_1.logger.debug(`Background state refresh failed: ${e}`); }); }, 1000); } return success; } else { // Use parent implementation for non-Vital models return super.turnOn(); } } /** * Override turn off method to handle Vital series special cases */ async turnOff() { logger_1.logger.info(`Turning off device: ${this.deviceName}`); const [head, body] = this.buildApiDict('setSwitch'); // For Vital series, use powerSwitch per YAML spec // For other models, use the parent class implementation if (this.isVitalSeries()) { logger_1.logger.debug(`Using Vital series specific payload for ${this.deviceName}`); body.payload.data = { powerSwitch: 0, switchIdx: 0 }; const [response, status] = await this.callApi('/cloud/v2/deviceManaged/bypassV2', 'post', body, head); // Use Vital-specific response checking const success = this.checkVitalResponse(response, status, 'turnOff'); if (success) { this.deviceStatus = 'off'; // Force a details update to sync state setTimeout(() => { this.getDetails().catch(e => { logger_1.logger.debug(`Background state refresh failed: ${e}`); }); }, 1000); } return success; } else { // Use parent implementation for non-Vital models return super.turnOff(); } } /** * Override setMode method to handle Vital series special cases */ async setMode(mode) { if (!this.modes.includes(mode)) { const error = `Invalid mode: ${mode}. Must be one of: ${this.modes.join(', ')}`; logger_1.logger.error(`${error} for device: ${this.deviceName}`); throw new Error(error); } // Special handling for Core200S stays the same for all models if (this.deviceType.includes('Core200S') && mode === 'auto') { logger_1.logger.warn(`Auto mode not supported for ${this.deviceType}, using manual mode instead`); return this.setMode('manual'); } // For Vital series, use special response handling // For other models, use the parent implementation if (this.isVitalSeries()) { logger_1.logger.debug(`Using Vital series specific response handling for ${this.deviceName}`); const [head, body] = this.buildApiDict('setPurifierMode'); body.payload.data = { workMode: mode }; const [response, status] = await this.callApi('/cloud/v2/deviceManaged/bypassV2', 'post', body, head); const success = this.checkVitalResponse(response, status, 'setMode'); if (success) { this.details.mode = mode; this._mode = mode; // Force a details update to sync state setTimeout(() => { this.getDetails().catch(e => { logger_1.logger.debug(`Background state refresh failed: ${e}`); }); }, 1000); return true; } else { logger_1.logger.error(`Failed to set mode to ${mode} for device: ${this.deviceName}`); return false; } } else { // Use parent implementation for non-Vital models return super.setMode(mode); } } /** * Override changeFanSpeed method to handle Vital series special cases */ async changeFanSpeed(speed) { var _a; const speeds = (_a = this.config.levels) !== null && _a !== void 0 ? _a : []; if (speeds.length > 0 && !speeds.includes(speed)) { logger_1.logger.error(`Invalid speed: ${speed}. Must be one of: ${speeds.join(', ')} for device: ${this.deviceName}`); return false; } logger_1.logger.info(`Changing fan speed to ${speed} for device: ${this.deviceName}`); const [head, body] = this.buildApiDict('setLevel'); // Specific handling for Vital series devices if (this.isVitalSeries()) { logger_1.logger.debug(`Using Vital series specific payload for ${this.deviceName}`); // For Vital series, use levelIdx, levelType, and manualSpeedLevel per YAML spec body.payload.data = { levelIdx: 0, levelType: 'wind', manualSpeedLevel: speed }; const [response, status] = await this.callApi('/cloud/v2/deviceManaged/bypassV2', 'post', body, head); const success = this.checkVitalResponse(response, status, 'changeFanSpeed'); if (success) { this.speed = speed; this.details.manualSpeedLevel = speed; // Force a details update to sync state setTimeout(() => { this.getDetails().catch(e => { logger_1.logger.debug(`Background state refresh failed: ${e}`); }); }, 1000); return true; } else { logger_1.logger.error(`Failed to change fan speed to ${speed} for device: ${this.deviceName}`); return false; } } else { // For non-Vital models, use id, level, mode, and type body.payload.data = { id: 0, level: speed, mode: 'manual', type: 'wind' }; const [response, status] = await this.callApi('/cloud/v2/deviceManaged/bypassV2', 'post', body, head); const success = this.checkResponse([response, status], 'changeFanSpeed'); if (success) { this.speed = speed; this.details.manualSpeedLevel = speed; return true; } else { logger_1.logger.error(`Failed to change fan speed to ${speed} for device: ${this.deviceName}`); return false; } } } /** * Set auto preference */ async setAutoPreference(preference = 'default', roomSize = 600) { if (!this.autoPreferences.includes(preference)) { logger_1.logger.debug(`Invalid preference: ${preference} - valid preferences are default, efficient, quiet`); return false; } const [head, body] = this.buildApiDict('setAutoPreference'); body.payload.data = { autoPreference: preference, roomSize: roomSize }; const [response, status] = await this.callApi('/cloud/v2/deviceManaged/bypassV2', 'post', body, head); // Use the appropriate response checking method based on device type const success = this.isVitalSeries() ? this.checkVitalResponse(response, status, 'setAutoPreference') : this.checkResponse([response, status], 'setAutoPreference'); if (success) { this.details.auto_preference = preference; this.details.auto_preference_type = preference; // Force a details update to sync state for Vital series if (this.isVitalSeries()) { setTimeout(() => { this.getDetails().catch(e => { logger_1.logger.debug(`Background state refresh failed: ${e}`); }); }, 1000); } } return success; } /** * Set light detection */ async setLightDetection(enabled) { const [head, body] = this.buildApiDict('setLightDetection'); body.payload.data = { lightDetectionSwitch: enabled ? 1 : 0 }; const [response, status] = await this.callApi('/cloud/v2/deviceManaged/bypassV2', 'post', body, head); // Use the appropriate response checking method based on device type const success = this.isVitalSeries() ? this.checkVitalResponse(response, status, 'setLightDetection') : this.checkResponse([response, status], 'setLightDetection'); if (success) { this.details.light_detection_switch = enabled; // Force a details update to sync state for Vital series if (this.isVitalSeries()) { setTimeout(() => { this.getDetails().catch(e => { logger_1.logger.debug(`Background state refresh failed: ${e}`); }); }, 1000); } } return success; } /** * Get light detection status */ get lightDetection() { return Boolean(this.details.light_detection_switch); } /** * Get light detection state */ get lightDetectionState() { return Boolean(this.details.environment_light_state); } /** * Get auto preference type */ get autoPreferenceType() { return this.details.auto_preference_type; } /** * Display JSON details */ displayJSON() { var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m; const baseInfo = JSON.parse(super.displayJSON()); const details = { ...baseInfo, 'Mode': this.mode, 'Filter Life': ((_a = this.details.filter_life) !== null && _a !== void 0 ? _a : 0).toString(), 'Fan Level': this.speed.toString(), 'Display On': (_c = (_b = this.details.display) === null || _b === void 0 ? void 0 : _b.toString()) !== null && _c !== void 0 ? _c : 'false', 'Child Lock': ((_d = this.details.child_lock) !== null && _d !== void 0 ? _d : false).toString(), 'Night Light': ((_e = this.details.night_light) !== null && _e !== void 0 ? _e : '').toString(), 'Display Set On': ((_f = this.details.screen_switch) !== null && _f !== void 0 ? _f : false).toString(), 'Light Detection Enabled': ((_g = this.details.light_detection_switch) !== null && _g !== void 0 ? _g : false).toString(), 'Environment Light State': ((_h = this.details.environment_light_state) !== null && _h !== void 0 ? _h : false).toString() }; if (this.hasFeature('air_quality')) { details['Air Quality Level'] = ((_j = this.details.air_quality) !== null && _j !== void 0 ? _j : '').toString(); details['Air Quality Value'] = ((_k = this.details.air_quality_value) !== null && _k !== void 0 ? _k : '').toString(); } const everestKeys = { 'pm1': 'PM1', 'pm10': 'PM10', 'fan_rotate_angle': 'Fan Rotate Angle', 'filter_open_state': 'Filter Open State' }; for (const [key, value] of Object.entries(everestKeys)) { if (key in this.details) { details[value] = (_m = (_l = this.details[key]) === null || _l === void 0 ? void 0 : _l.toString()) !== null && _m !== void 0 ? _m : ''; } } return JSON.stringify(details, null, 4); } /** * Set oscillation state */ async setOscillation(toggle) { logger_1.logger.debug(`Setting oscillation to ${toggle ? 'on' : 'off'} for device: ${this.deviceName}`); const [head, body] = this.buildApiDict('setSwitch'); body.payload.data = { oscillationSwitch: toggle ? 1 : 0, switchIdx: 0 }; const [response, status] = await this.callApi('/cloud/v2/deviceManaged/bypassV2', 'post', body, head); // Use the appropriate response checking method based on device type const success = this.isVitalSeries() ? this.checkVitalResponse(response, status, 'setOscillation') : this.checkResponse([response, status], 'setOscillation'); if (success) { this.details.oscillationState = toggle; this.details.oscillationSwitch = toggle ? 1 : 0; } return success; } } exports.VeSyncAirBaseV2 = VeSyncAirBaseV2;