Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Optimize 3.5 detection and prevent crashes #690

Open
wants to merge 7 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 12 additions & 4 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,7 @@ class TuyaDevice extends EventEmitter {
* @example
* // get all available data from device
* tuya.get({schema: true}).then(data => console.log(data))
* @returns {Promise<Boolean|Object>}
* @returns {Promise<Boolean|undefined|Object>}
* returns boolean if single property is requested, otherwise returns object of results
*/
async get(options = {}) {
Expand Down Expand Up @@ -194,7 +194,7 @@ class TuyaDevice extends EventEmitter {
}

// Return first property by default
return data.dps['1'];
return data.dps ? data.dps['1'] : undefined;
}

/**
Expand Down Expand Up @@ -525,8 +525,10 @@ class TuyaDevice extends EventEmitter {
// Send ping
this.client.write(buffer);
if (this.globalOptions.issueRefreshOnPing) {
this.refresh();
this.get();
this.refresh().then(() => this.get()).catch(error => {
debug('Error refreshing/getting on ping: ' + error);
this.emit('error', error);
});
}
}

Expand Down Expand Up @@ -1017,11 +1019,17 @@ class TuyaDevice extends EventEmitter {
} catch (error) {
debug(error);
reject(error);
return;
}

debug('UDP data:');
debug(dataRes);

if (typeof dataRes.payload === 'string') {
debug('Received string payload. Ignoring.');
return;
}

const thisID = dataRes.payload.gwId;
const thisIP = dataRes.payload.ip;

Expand Down
18 changes: 10 additions & 8 deletions lib/cipher.js
Original file line number Diff line number Diff line change
Expand Up @@ -112,17 +112,19 @@ class TuyaCipher {
}

/**
* Decrypts data.
* @param {String|Buffer} data to decrypt
* @returns {Object|String}
* returns object if data is JSON, else returns string
*/
decrypt(data) {
if (this.version === '3.4') {
* Decrypts data.
* @param {String|Buffer} data to decrypt
* @param {String} [version] protocol version
* @returns {Object|String}
* returns object if data is JSON, else returns string
*/
decrypt(data, version) {
version = version || this.version;
if (version === '3.4') {
return this._decrypt34(data);
}

if (this.version === '3.5') {
if (version === '3.5') {
return this._decrypt35(data);
}

Expand Down
19 changes: 13 additions & 6 deletions lib/message-parser.js
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,7 @@ class MessageParser {
let sequenceN;
let commandByte;
let payloadSize;
let overwriteVersion;

if (suffix === 0x0000AA55) {
// Get sequence number
Expand All @@ -154,6 +155,9 @@ class MessageParser {
throw new TypeError(`Packet missing payload: payload has length ${payloadSize}.`);
}
} else if (suffix === 0x00009966) {
// When this suffix comes in we should have 3.5 version
overwriteVersion = '3.5';

// Get sequence number
sequenceN = buffer.readUInt32BE(6);

Expand All @@ -167,6 +171,8 @@ class MessageParser {
if (buffer.length - 8 < payloadSize) {
throw new TypeError(`Packet missing payload: payload has length ${payloadSize}.`);
}
} else {
throw new TypeError(`Suffix does not match: ${buffer.toString('hex')}`); // Should never happen
}

const packageFromDiscovery = (
Expand All @@ -183,7 +189,7 @@ class MessageParser {
// Get the payload
// Adjust for messages lacking a return code
let payload;
if (this.version === '3.5') {
if (overwriteVersion === '3.5' || this.version === '3.5') {
payload = buffer.slice(HEADER_SIZE_3_5, HEADER_SIZE_3_5 + payloadSize);
sequenceN = buffer.slice(6, 10).readUInt32BE();
commandByte = buffer.slice(10, 14).readUInt32BE();
Expand Down Expand Up @@ -222,17 +228,18 @@ class MessageParser {
}
}

return {payload, leftover, commandByte, sequenceN};
return {payload, leftover, commandByte, sequenceN, version: overwriteVersion || this.version};
}

/**
* Attempts to decode a given payload into
* an object or string.
* @param {Buffer} data to decode
* @param {String} version of protocol
* @returns {Object|String}
* object if payload is JSON, otherwise string
*/
getPayload(data) {
getPayload(data, version) {
if (data.length === 0) {
return false;
}
Expand All @@ -243,13 +250,13 @@ class MessageParser {
throw new Error('Missing key or version in constructor.');
}

data = this.cipher.decrypt(data);
data = this.cipher.decrypt(data, version);
} catch (_) {
data = data.toString('utf8');
}

// Incoming 3.5 data isn't 0 because of iv and tag so check size after
if (this.version === '3.5') {
if (version === '3.5') {
if (data.length === 0) {
return false;
}
Expand Down Expand Up @@ -279,7 +286,7 @@ class MessageParser {
parseRecursive(buffer, packets) {
const result = this.parsePacket(buffer);

result.payload = this.getPayload(result.payload);
result.payload = this.getPayload(result.payload, result.version);

packets.push(result);

Expand Down
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@
},
"homepage": "https://github.com/codetheweb/tuyapi#readme",
"dependencies": {
"debug": "^4.3.7",
"debug": "^4.4.0",
"p-queue": "6.6.2",
"p-retry": "4.6.2",
"p-timeout": "3.2.0"
Expand All @@ -49,7 +49,7 @@
"clone": "2.1.2",
"coveralls": "3.1.1",
"delay": "4.4.1",
"documentation": "^14.0.0",
"documentation": "^14.0.3",
"nyc": "15.1.0",
"xo": "0.25.4"
},
Expand Down