tsvesync
Version:
A TypeScript library for interacting with VeSync smart home devices
570 lines (569 loc) • 22.5 kB
JavaScript
"use strict";
/**
* VeSync API Device Library
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.VeSync = void 0;
const helpers_1 = require("./helpers");
const vesyncFanImpl_1 = require("./vesyncFanImpl");
const vesyncOutletImpl_1 = require("./vesyncOutletImpl");
const vesyncSwitchImpl_1 = require("./vesyncSwitchImpl");
const vesyncBulbImpl_1 = require("./vesyncBulbImpl");
const logger_1 = require("./logger");
const DEFAULT_ENERGY_UPDATE_INTERVAL = 21600;
/**
* Create device instance based on type
*/
function objectFactory(details, manager) {
const deviceType = details.deviceType;
let DeviceClass = null;
let category = 'unknown';
// Map of device categories to their module dictionaries
const allModules = {
outlets: vesyncOutletImpl_1.outletModules,
fans: vesyncFanImpl_1.fanModules,
bulbs: vesyncBulbImpl_1.bulbModules,
switches: vesyncSwitchImpl_1.switchModules
};
// First try exact match in all modules
for (const [cat, modules] of Object.entries(allModules)) {
if (deviceType in modules) {
DeviceClass = modules[deviceType];
category = cat;
logger_1.logger.debug(`Found exact match for ${deviceType} in ${cat} modules`);
break;
}
}
// If no exact match, try to find a base class
if (!DeviceClass) {
// Device type prefix mapping
const prefixMap = {
// Fans
'Core': 'fans',
'LAP': 'fans',
'LTF': 'fans',
'Classic': 'fans',
'Dual': 'fans',
'LUH': 'fans',
'LEH': 'fans',
'LV-PUR': 'fans',
'LV-RH': 'fans',
// Outlets
'wifi-switch': 'outlets',
'ESW03': 'outlets',
'ESW01': 'outlets',
'ESW10': 'outlets',
'ESW15': 'outlets',
'ESO': 'outlets',
// Switches
'ESWL': 'switches',
'ESWD': 'switches',
// Bulbs
'ESL': 'bulbs',
'XYD': 'bulbs'
};
// Find category based on device type prefix
for (const [prefix, cat] of Object.entries(prefixMap)) {
if (deviceType.startsWith(prefix)) {
category = cat;
logger_1.logger.debug(`Device type ${deviceType} matched prefix ${prefix} -> category ${cat}`);
// Try to find a base class in this category's modules
const modules = allModules[cat];
for (const [moduleType, ModuleClass] of Object.entries(modules)) {
const baseType = moduleType.split('-')[0]; // e.g., ESL100 from ESL100-USA
if (deviceType.startsWith(baseType)) {
DeviceClass = ModuleClass;
logger_1.logger.debug(`Found base type match: ${deviceType} -> ${baseType}`);
break;
}
}
break;
}
}
}
if (DeviceClass) {
try {
// Add category to device details
details.deviceCategory = category;
// Handle outdoor plug sub-devices
if (deviceType === 'ESO15-TB' && details.subDeviceNo) {
const devices = [];
// Create a device instance for each sub-device
const subDeviceDetails = {
...details,
deviceName: details.deviceName,
deviceStatus: details.deviceStatus,
subDeviceNo: details.subDeviceNo,
isSubDevice: true
};
const device = new DeviceClass(subDeviceDetails, manager);
devices.push([category, device]);
// Return array of sub-devices
return devices[0]; // Return first device, manager will handle adding all devices
}
else {
const device = new DeviceClass(details, manager);
return [category, device];
}
}
catch (error) {
logger_1.logger.error(`Error creating device instance for ${deviceType}:`, error);
return [category, null];
}
}
else {
logger_1.logger.debug(`No device class found for type: ${deviceType}`);
return [category, null];
}
}
/**
* VeSync Manager Class
*/
class VeSync {
/**
* Initialize VeSync Manager
* @param username - VeSync account username
* @param password - VeSync account password
* @param timeZone - Optional timezone for device operations (defaults to America/New_York)
* @param debug - Optional debug mode flag
* @param redact - Optional redact mode flag
* @param apiUrl - Optional API base URL override
* @param customLogger - Optional custom logger implementation
* @param excludeConfig - Optional device exclusion configuration
*/
constructor(username, password, timeZone = helpers_1.DEFAULT_TZ, debug = false, redact = true, apiUrl, customLogger, excludeConfig) {
this._debug = debug;
this._redact = redact;
this._energyUpdateInterval = DEFAULT_ENERGY_UPDATE_INTERVAL;
this._energyCheck = true;
this._lastUpdateTs = null;
this._inProcess = false;
this._excludeConfig = excludeConfig || null;
this.username = username;
this.password = password;
this.token = null;
this.accountId = null;
this.countryCode = null;
this.devices = null;
this.enabled = false;
this.updateInterval = helpers_1.API_RATE_LIMIT;
this.fans = [];
this.outlets = [];
this.switches = [];
this.bulbs = [];
this.scales = [];
this._devList = {
fans: this.fans,
outlets: this.outlets,
switches: this.switches,
bulbs: this.bulbs
};
// Set timezone first
if (typeof timeZone === 'string' && timeZone) {
const regTest = /[^a-zA-Z/_]/;
if (regTest.test(timeZone)) {
this.timeZone = helpers_1.DEFAULT_TZ;
logger_1.logger.debug('Invalid characters in time zone - ', timeZone);
}
else {
this.timeZone = timeZone;
}
}
else {
this.timeZone = helpers_1.DEFAULT_TZ;
logger_1.logger.debug('Time zone is not a string');
}
// Set custom API URL if provided, otherwise use default US endpoint
if (apiUrl) {
(0, helpers_1.setApiBaseUrl)(apiUrl);
}
else {
// Always use US endpoint
(0, helpers_1.setApiBaseUrl)('https://smartapi.vesync.com');
}
// Set custom logger if provided
if (customLogger) {
(0, logger_1.setLogger)(customLogger);
}
if (debug) {
this.debug = true;
}
if (redact) {
this.redact = true;
}
}
/**
* Get/Set debug mode
*/
get debug() {
return this._debug;
}
set debug(flag) {
this._debug = flag;
}
/**
* Get/Set redact mode
*/
get redact() {
return this._redact;
}
set redact(flag) {
this._redact = flag;
helpers_1.Helpers.shouldRedact = flag;
}
/**
* Get/Set energy update interval
*/
get energyUpdateInterval() {
return this._energyUpdateInterval;
}
set energyUpdateInterval(interval) {
if (interval > 0) {
this._energyUpdateInterval = interval;
}
}
/**
* Test if device should be removed
*/
static removeDevTest(device, newList) {
if (Array.isArray(newList) && device.cid) {
for (const item of newList) {
if ('cid' in item && device.cid === item.cid) {
return true;
}
}
logger_1.logger.debug(`Device removed - ${device.deviceName} - ${device.deviceType}`);
return false;
}
return true;
}
/**
* Test if new device should be added
*/
addDevTest(newDev) {
if ('cid' in newDev) {
for (const devices of Object.values(this._devList)) {
for (const dev of devices) {
if (dev.cid === newDev.cid) {
return false;
}
}
}
}
return true;
}
/**
* Remove devices not found in device list return
*/
removeOldDevices(devices) {
for (const [key, deviceList] of Object.entries(this._devList)) {
const before = deviceList.length;
this._devList[key] = deviceList.filter(device => VeSync.removeDevTest(device, devices));
const after = this._devList[key].length;
if (before !== after) {
logger_1.logger.debug(`${before - after} ${key} removed`);
}
}
return true;
}
/**
* Correct devices without cid or uuid
*/
static setDevId(devices) {
const devRem = [];
devices.forEach((dev, index) => {
if (!dev.cid) {
if (dev.macID) {
dev.cid = dev.macID;
}
else if (dev.uuid) {
dev.cid = dev.uuid;
}
else {
devRem.push(index);
logger_1.logger.warn(`Device with no ID - ${dev.deviceName || ''}`);
}
}
});
if (devRem.length > 0) {
return devices.filter((_, index) => !devRem.includes(index));
}
return devices;
}
/**
* Process devices from API response
*/
processDevices(deviceList) {
try {
// Clear existing devices
for (const category of Object.keys(this._devList)) {
this._devList[category].length = 0;
}
if (!deviceList || deviceList.length === 0) {
logger_1.logger.warn('No devices found in API response');
return false;
}
// Process each device
deviceList.forEach(dev => {
const [category, device] = objectFactory(dev, this);
// Handle outdoor plug sub-devices
if (dev.deviceType === 'ESO15-TB' && dev.subDeviceNo) {
const subDeviceDetails = {
...dev,
deviceName: dev.deviceName,
deviceStatus: dev.deviceStatus,
subDeviceNo: dev.subDeviceNo,
isSubDevice: true,
};
const [subCategory, subDevice] = objectFactory(subDeviceDetails, this);
if (subDevice && subCategory in this._devList) {
this._devList[subCategory].push(subDevice);
}
}
else if (device && category in this._devList) {
this._devList[category].push(device);
}
});
// Update device list reference
this.devices = Object.values(this._devList).flat();
// Return true if we processed at least one device successfully
return this.devices.length > 0;
}
catch (error) {
logger_1.logger.error('Error processing devices:', error);
return false;
}
}
/**
* Get list of VeSync devices
*/
async getDevices() {
var _a, _b;
if (!this.enabled) {
logger_1.logger.error('Not logged in to VeSync');
return false;
}
this._inProcess = true;
let success = false;
try {
const [response] = await helpers_1.Helpers.callApi('/cloud/v2/deviceManaged/devices', 'post', helpers_1.Helpers.reqBody(this, 'devicelist'), helpers_1.Helpers.reqHeaders(this), this);
if (!response) {
logger_1.logger.error('No response received from VeSync API');
return false;
}
if (response.error) {
logger_1.logger.error('API error:', response.msg || 'Unknown error');
return false;
}
if (!((_a = response.result) === null || _a === void 0 ? void 0 : _a.list)) {
logger_1.logger.error('No device list found in response');
return false;
}
const deviceList = response.result.list;
success = this.processDevices(deviceList);
if (success) {
// Log device discovery results
logger_1.logger.debug('\n=== Device Discovery Summary ===');
logger_1.logger.debug(`Total devices processed: ${deviceList.length}`);
// Log device types found
const deviceTypes = deviceList.map((d) => d.deviceType);
logger_1.logger.debug('\nDevice types found:', deviceTypes);
// Log devices by category with details
logger_1.logger.debug('\nDevices by Category:');
logger_1.logger.debug('---------------------');
for (const [category, devices] of Object.entries(this._devList)) {
if (devices.length > 0) {
logger_1.logger.debug(`\n${category.toUpperCase()} (${devices.length} devices):`);
devices.forEach((d) => {
logger_1.logger.debug(` • ${d.deviceName}`);
logger_1.logger.debug(` Type: ${d.deviceType}`);
logger_1.logger.debug(` Status: ${d.deviceStatus}`);
logger_1.logger.debug(` ID: ${d.cid}`);
});
}
}
// Log summary statistics
logger_1.logger.debug('\nSummary Statistics:');
logger_1.logger.debug('-------------------');
logger_1.logger.debug(`Total Devices: ${((_b = this.devices) === null || _b === void 0 ? void 0 : _b.length) || 0}`);
for (const [category, devices] of Object.entries(this._devList)) {
logger_1.logger.debug(`${category}: ${devices.length} devices`);
}
logger_1.logger.debug('\n=== End of Device Discovery ===\n');
}
}
catch (err) {
const error = err;
if (error.code === 'ECONNABORTED') {
logger_1.logger.error('VeSync API request timed out');
}
else if (error.code === 'ECONNREFUSED') {
logger_1.logger.error('Unable to connect to VeSync API');
}
else {
logger_1.logger.error('Error getting device list:', error.message || 'Unknown error');
}
}
this._inProcess = false;
return success;
}
/**
* Login to VeSync server
*/
async login(retryAttempts = 3, initialDelayMs = 1000) {
var _a;
const body = helpers_1.Helpers.reqBody(this, 'login');
for (let attempt = 0; attempt < retryAttempts; attempt++) {
try {
logger_1.logger.debug('Login attempt', {
attempt: attempt + 1,
apiUrl: (0, helpers_1.getApiBaseUrl)(),
timeZone: this.timeZone,
appVersion: body.appVersion
});
const [response, status] = await helpers_1.Helpers.callApi('/cloud/v1/user/login', 'post', body, {}, this);
logger_1.logger.debug('Login response:', { status, response });
// Handle specific error codes
if (response && response.code) {
switch (response.code) {
case -11012022:
logger_1.logger.error('App version too low error. Current version:', body.appVersion);
logger_1.logger.error('This typically indicates an API version compatibility issue.');
break;
case -11003:
logger_1.logger.error('Authentication failed - check credentials');
break;
case -11001:
logger_1.logger.error('Invalid request format');
break;
default:
logger_1.logger.error('API error code:', response.code, 'message:', response.msg);
}
}
if ((_a = response === null || response === void 0 ? void 0 : response.result) === null || _a === void 0 ? void 0 : _a.token) {
this.token = response.result.token;
this.accountId = response.result.accountID;
this.countryCode = response.result.countryCode;
this.enabled = true;
logger_1.logger.debug('Login successful for region:', this.countryCode);
return true;
}
// If we reach here, login failed but didn't throw an error
const delay = initialDelayMs * Math.pow(2, attempt);
logger_1.logger.debug(`Login attempt ${attempt + 1} failed, retrying in ${delay}ms...`);
await new Promise(resolve => setTimeout(resolve, delay));
}
catch (error) {
if (attempt === retryAttempts - 1) {
logger_1.logger.error('Login error after all retry attempts:', error);
return false;
}
const delay = initialDelayMs * Math.pow(2, attempt);
logger_1.logger.debug(`Login attempt ${attempt + 1} failed with error, retrying in ${delay}ms...`, error);
await new Promise(resolve => setTimeout(resolve, delay));
}
}
logger_1.logger.error('Unable to login with supplied credentials after all retry attempts');
return false;
}
/**
* Test if update interval has been exceeded
*/
deviceTimeCheck() {
return (this._lastUpdateTs === null ||
(Date.now() - this._lastUpdateTs) / 1000 > this.updateInterval);
}
/**
* Check if a device should be excluded based on configuration
*/
shouldExcludeDevice(device) {
var _a, _b, _c, _d, _e;
if (!this._excludeConfig) {
return false;
}
const exclude = this._excludeConfig;
// Check device type
if ((_a = exclude.type) === null || _a === void 0 ? void 0 : _a.includes(device.deviceType.toLowerCase())) {
logger_1.logger.debug(`Excluding device ${device.deviceName} by type: ${device.deviceType}`);
return true;
}
// Check device model
if ((_b = exclude.model) === null || _b === void 0 ? void 0 : _b.some(model => device.deviceType.toUpperCase().includes(model.toUpperCase()))) {
logger_1.logger.debug(`Excluding device ${device.deviceName} by model: ${device.deviceType}`);
return true;
}
// Check exact name match
if ((_c = exclude.name) === null || _c === void 0 ? void 0 : _c.includes(device.deviceName.trim())) {
logger_1.logger.debug(`Excluding device ${device.deviceName} by exact name match`);
return true;
}
// Check name patterns
if (exclude.namePattern) {
for (const pattern of exclude.namePattern) {
try {
const regex = new RegExp(pattern);
if (regex.test(device.deviceName.trim())) {
logger_1.logger.debug(`Excluding device ${device.deviceName} by name pattern: ${pattern}`);
return true;
}
}
catch (error) {
logger_1.logger.warn(`Invalid regex pattern in exclude config: ${pattern}`);
}
}
}
// Check device ID (cid or uuid)
if (((_d = exclude.id) === null || _d === void 0 ? void 0 : _d.includes(device.cid)) || ((_e = exclude.id) === null || _e === void 0 ? void 0 : _e.includes(device.uuid))) {
logger_1.logger.debug(`Excluding device ${device.deviceName} by ID: ${device.cid}/${device.uuid}`);
return true;
}
return false;
}
/**
* Update device list and details
*/
async update() {
if (this.deviceTimeCheck()) {
if (!this.enabled) {
logger_1.logger.error('Not logged in to VeSync');
return;
}
await this.getDevices();
logger_1.logger.debug('Start updating the device details one by one');
for (const deviceList of Object.values(this._devList)) {
for (const device of deviceList) {
try {
if (!this.shouldExcludeDevice(device)) {
await device.getDetails();
}
else {
logger_1.logger.debug(`Skipping details update for excluded device: ${device.deviceName}`);
}
}
catch (error) {
logger_1.logger.error(`Error updating ${device.deviceName}:`, error);
}
}
}
this._lastUpdateTs = Date.now();
}
}
/**
* Create device instance from details
*/
createDevice(details) {
const deviceType = details.deviceType;
const deviceClass = vesyncFanImpl_1.fanModules[deviceType];
if (deviceClass) {
return new deviceClass(details, this);
}
return null;
}
/**
* Call API with authentication
*/
async callApi(endpoint, method, data = null, headers = {}) {
return await helpers_1.Helpers.callApi(endpoint, method, data, headers, this);
}
}
exports.VeSync = VeSync;