Skip to content

Commit

Permalink
Add debug and debugLevel options.
Browse files Browse the repository at this point in the history
  • Loading branch information
0x5e committed Jul 11, 2023
1 parent 91386aa commit 1d32f13
Show file tree
Hide file tree
Showing 12 changed files with 92 additions and 85 deletions.
16 changes: 7 additions & 9 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,8 @@ Before you can configure, you must go to the [Tuya IoT Platform](https://iot.tuy
- `options.endpoint` - **required** : The endpoint URL taken from the [API Reference > Endpoints](https://developer.tuya.com/en/docs/iot/api-request?id=Ka4a8uuo1j4t4#title-1-Endpoints) table.
- `options.accessId` - **required** : The Access ID obtained from [Tuya IoT Platform > Cloud Develop](https://iot.tuya.com/cloud)
- `options.accessKey` - **required** : The Access Secret obtained from [Tuya IoT Platform > Cloud Develop](https://iot.tuya.com/cloud)
- `options.debug` - **optional**: Includes debugging output in the Homebridge log. (Default: `false`)
- `options.debugLevel` - **optional**: An optional list of strings seperated with comma `,`. `api` represents for HTTP API log, `mqtt` represents for MQTT log, and device ID represents for device log. If blank, all logs are outputed.

#### For "Smart Home" Project

Expand All @@ -88,7 +90,9 @@ Before you can configure, you must go to the [Tuya IoT Platform](https://iot.tuy
- `options.password` - **required** : The app account's password. MD5 salted password is also available for increased security.
- `options.appSchema` - **required** : The app schema: 'tuyaSmart' for the Tuya Smart App, or 'smartlife' for the Smart Life App.
- `options.endpoint` - **optional** : The endpoint URL can be inferred from the [API Reference > Endpoints](https://developer.tuya.com/en/docs/iot/api-request?id=Ka4a8uuo1j4t4#title-1-Endpoints) table based on the country code provided. Only manually set this value if you encounter login issues and need to specify the endpoint for your account location.
- `options.homeWhitelist` - **optional**: An array of integer values for the home IDs you want to whitelist. If provided, only devices with matching Home IDs will be included. You can find the Home ID in the homebridge log.
- `options.homeWhitelist` - **optional**: An array of integer values for the home IDs you want to whitelist. If provided, only devices with matching Home IDs will be included. You can find the Home ID in the Homebridge log.
- `options.debug` - **optional**: Includes debugging output in the Homebridge log. (Default: `false`)
- `options.debugLevel` - **optional**: An optional list of strings seperated with comma `,`. `api` represents for API and MQTT log, device ID represents for specific device log. If blank, all logs are outputed.


#### Advanced options
Expand Down Expand Up @@ -160,15 +164,9 @@ After Homebridge has been successfully launched, the device information list wil
**⚠️Please make sure to remove sensitive information such as `ip`, `lon`, `lat`, `local_key`, and `uid` before submitting the file.**


#### 2. Enable Homebridge Debug Mode
#### 2. Enable Debug Mode

For Homebridge Web UI users:
- Go to the `Homebridge Setting` page
- Turn on the `Homebridge Debug Mode -D` switch
- Restart Homebridge.

For Homebridge Command Line Users:
- Start Homebridge with the `-D` flag: `homebridge -D`
Add debug option in the plugin config, then restart Homebridge.

#### 3. Collect Logs

Expand Down
10 changes: 10 additions & 0 deletions config.schema.json
Original file line number Diff line number Diff line change
Expand Up @@ -268,6 +268,16 @@
}
}
}
},
"debug": {
"title": "Enable Debug Logging",
"type": "boolean",
"default": false
},
"debugLevel": {
"title": "Debug Level",
"description": "An optional list of strings seperated with comma `,`. `api` represents for API and MQTT log, device ID represents for specific device log. If blank, all logs are outputed.",
"type": "string"
}
}
}
Expand Down
9 changes: 8 additions & 1 deletion src/accessory/BaseAccessory.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,14 @@ class BaseAccessory {

public deviceManager = this.platform.deviceManager!;
public device = this.deviceManager.getDevice(this.accessory.context.deviceID)!;
public log = new PrefixLogger(this.platform.log, this.device.name.length > 0 ? this.device.name : this.device.id);
public log = new PrefixLogger(
this.platform.log,
this.device.name.length > 0 ? this.device.name : this.device.id,
this.platform.options.debug && ((this.platform.options.debugLevel ?? '').length > 0
? this.platform.options.debugLevel?.includes(this.device.id)
: true),
);

public intialized = false;

public adaptiveLightingController?;
Expand Down
8 changes: 8 additions & 0 deletions src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,8 @@ export interface TuyaPlatformCustomConfigOptions {
username: string;
password: string;
deviceOverrides?: Array<TuyaPlatformDeviceConfig>;
debug?: boolean;
debugLevel?: string;
}

export interface TuyaPlatformHomeConfigOptions {
Expand All @@ -40,6 +42,8 @@ export interface TuyaPlatformHomeConfigOptions {
appSchema: string;
homeWhitelist?: Array<number>;
deviceOverrides?: Array<TuyaPlatformDeviceConfig>;
debug?: boolean;
debugLevel?: string;
}

export type TuyaPlatformConfigOptions = TuyaPlatformCustomConfigOptions | TuyaPlatformHomeConfigOptions;
Expand All @@ -54,6 +58,8 @@ export const customOptionsSchema = {
accessId: { type: 'string', required: true },
accessKey: { type: 'string', required: true },
deviceOverrides: { 'type': 'array' },
debug: { type: 'boolean' },
debugLevel: { 'type': 'string' },
},
};

Expand All @@ -68,5 +74,7 @@ export const homeOptionsSchema = {
appSchema: { 'type': 'string', required: true },
homeWhitelist: { 'type': 'array' },
deviceOverrides: { 'type': 'array' },
debug: { type: 'boolean' },
debugLevel: { 'type': 'string' },
},
};
3 changes: 2 additions & 1 deletion src/core/TuyaOpenAPI.ts
Original file line number Diff line number Diff line change
Expand Up @@ -85,8 +85,9 @@ export default class TuyaOpenAPI {
public accessKey: string,
public log: Logger = console,
public lang = 'en',
public debug = false,
) {
this.log = new PrefixLogger(log, TuyaOpenAPI.name);
this.log = new PrefixLogger(log, TuyaOpenAPI.name, debug);
}

static getDefaultEndpoint(countryCode: number) {
Expand Down
3 changes: 2 additions & 1 deletion src/core/TuyaOpenMQ.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,8 +37,9 @@ export default class TuyaOpenMQ {
constructor(
public api: TuyaOpenAPI,
public log: Logger = console,
public debug = false,
) {
this.log = new PrefixLogger(log, TuyaOpenMQ.name);
this.log = new PrefixLogger(log, TuyaOpenMQ.name, debug);
}

start() {
Expand Down
3 changes: 2 additions & 1 deletion src/device/TuyaCustomDeviceManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,9 @@ export default class TuyaCustomDeviceManager extends TuyaDeviceManager {

constructor(
public api: TuyaOpenAPI,
public debug = false,
) {
super(api);
super(api, debug);
this.mq.version = '2.0';
}

Expand Down
3 changes: 2 additions & 1 deletion src/device/TuyaDeviceManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,11 +32,12 @@ export default class TuyaDeviceManager extends EventEmitter {

constructor(
public api: TuyaOpenAPI,
public debug = false,
) {
super();

const log = (this.api.log as PrefixLogger).log;
this.log = new PrefixLogger(log, TuyaDeviceManager.name);
this.log = new PrefixLogger(log, TuyaDeviceManager.name, debug);

this.mq = new TuyaOpenMQ(api, log);
this.mq.addMessageListener(this.onMQTTMessage.bind(this));
Expand Down
16 changes: 10 additions & 6 deletions src/platform.ts
Original file line number Diff line number Diff line change
Expand Up @@ -253,9 +253,10 @@ export class TuyaPlatform implements DynamicPlatformPlugin {
const DEFAULT_PASS = 'homebridge';

let res;
const { endpoint, accessId, accessKey } = this.options;
const api = new TuyaOpenAPI(endpoint, accessId, accessKey, this.log);
const deviceManager = new TuyaCustomDeviceManager(api);
const { endpoint, accessId, accessKey, debug, debugLevel } = this.options;
const debugMode = debug && ((debugLevel ?? '').length > 0 ? debugLevel?.includes('api') : true);
const api = new TuyaOpenAPI(endpoint, accessId, accessKey, this.log, 'en', debugMode);
const deviceManager = new TuyaCustomDeviceManager(api, debugMode);

this.log.info('Get token.');
res = await api.getToken();
Expand Down Expand Up @@ -341,13 +342,16 @@ export class TuyaPlatform implements DynamicPlatformPlugin {
}

let res;
const { accessId, accessKey, countryCode, username, password, appSchema, endpoint } = this.options;
const { accessId, accessKey, countryCode, username, password, appSchema, endpoint, debug, debugLevel } = this.options;
const debugMode = debug && ((debugLevel ?? '').length > 0 ? debugLevel?.includes('api') : true);
const api = new TuyaOpenAPI(
(endpoint && endpoint.length > 0) ? endpoint : TuyaOpenAPI.getDefaultEndpoint(countryCode),
accessId,
accessKey,
this.log);
const deviceManager = new TuyaHomeDeviceManager(api);
this.log,
'en',
debugMode);
const deviceManager = new TuyaHomeDeviceManager(api, debugMode);

this.log.info('Log in to Tuya Cloud.');
res = await api.homeLogin(countryCode, username, password, appSchema);
Expand Down
26 changes: 11 additions & 15 deletions src/util/FfmpegStreamingProcess.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,17 +36,15 @@ export class FfmpegStreamingProcess {
readonly stdin: Writable;

constructor(
cameraName: string,
sessionId: string,
videoProcessor: string,
ffmpegArgs: string[],
log: PrefixLogger,
debug = false,
delegate: StreamingDelegate,
callback?: StreamRequestCallback,
) {

log.debug('Stream command: ' + videoProcessor + ' ' + ffmpegArgs.join(' '), cameraName, debug);
log.debug(`Stream command: ${videoProcessor} ${ffmpegArgs.map(value => JSON.stringify(value)).join(' ')}`);

let started = false;
const startTime = Date.now();
Expand All @@ -63,11 +61,11 @@ export class FfmpegStreamingProcess {
const runtime = (Date.now() - startTime) / 1000;
const message = 'Getting the first frames took ' + runtime + ' seconds.';
if (runtime < 5) {
log.debug(message, cameraName, debug);
log.debug(message);
} else if (runtime < 22) {
log.warn(message, cameraName);
log.warn(message);
} else {
log.error(message, cameraName);
log.error(message);
}
}
}
Expand All @@ -81,14 +79,12 @@ export class FfmpegStreamingProcess {
callback();
callback = undefined;
}
if (debug && line.match(/\[(panic|fatal|error)\]/)) { // For now only write anything out when debug is set
log.error(line, cameraName);
} else if (debug) {
log.debug(line, cameraName, true);
if (line.match(/\[(panic|fatal|error)\]/)) {
log.error(line);
}
});
this.process.on('error', (error: Error) => {
log.error('FFmpeg process creation failed: ' + error.message, cameraName);
log.error('FFmpeg process creation failed: ' + error.message);
if (callback) {
callback(new Error('FFmpeg process creation failed'));
}
Expand All @@ -102,15 +98,15 @@ export class FfmpegStreamingProcess {
const message = 'FFmpeg exited with code: ' + code + ' and signal: ' + signal;

if (this.killTimeout && code === 0) {
log.debug(message + ' (Expected)', cameraName, debug);
log.debug(message + ' (Expected)');
} else if (code === null || code === 255) {
if (this.process.killed) {
log.debug(message + ' (Forced)', cameraName, debug);
log.debug(message + ' (Forced)');
} else {
log.error(message + ' (Unexpected)', cameraName);
log.error(message + ' (Unexpected)');
}
} else {
log.error(message + ' (Error)', cameraName);
log.error(message + ' (Error)');
delegate.stopStream(sessionId);
if (!started && callback) {
callback(new Error(message));
Expand Down
13 changes: 9 additions & 4 deletions src/util/Logger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,17 @@ export class PrefixLogger {
constructor(
public log: Logger,
public prefix: string,
public debugMode = false,
) {
this.debugMode = this.debugMode || process.argv.includes('-D') || process.argv.includes('--debug');
}

debug(message?: any, ...args: any[]) {
if (this.debugMode) {
this.log.info((this.prefix ? `[${this.prefix}] ` : '') + message, ...args);
} else {
this.log.debug((this.prefix ? `[${this.prefix}] ` : '') + message, ...args);
}
}

info(message?: any, ...args: any[]) {
Expand All @@ -27,8 +36,4 @@ export class PrefixLogger {
this.log.error((this.prefix ? `[${this.prefix}] ` : '') + message, ...args);
}

debug(message?: any, ...args: any[]) {
this.log.debug((this.prefix ? `[${this.prefix}] ` : '') + message, ...args);
}

}
Loading

0 comments on commit 1d32f13

Please sign in to comment.