* Encodes a payload into a Tuya-protocol-compliant packet for protocol version 3.3 and below. * @param {Object} options Options for encoding * @param {Buffer|String|Object} options.data data to encode * @param {Boolean} options.encrypted whether or not to encrypt the data * @param {Numbe
(options)
| 348 | * @returns {Buffer} Encoded Buffer |
| 349 | */ |
| 350 | _encodePre34(options) { |
| 351 | // Construct payload |
| 352 | let payload = options.data; |
| 353 | |
| 354 | // Protocol 3.3 and 3.2 is always encrypted |
| 355 | if (this.version === '3.3' || this.version === '3.2') { |
| 356 | // Encrypt data |
| 357 | payload = this.cipher.encrypt({ |
| 358 | data: payload, |
| 359 | base64: false |
| 360 | }); |
| 361 | |
| 362 | // Check if we need an extended header, only for certain CommandTypes |
| 363 | if (options.commandByte !== CommandType.DP_QUERY && |
| 364 | options.commandByte !== CommandType.DP_REFRESH) { |
| 365 | // Add 3.3 header |
| 366 | const buffer = Buffer.alloc(payload.length + 15); |
| 367 | Buffer.from('3.3').copy(buffer, 0); |
| 368 | payload.copy(buffer, 15); |
| 369 | payload = buffer; |
| 370 | } |
| 371 | } else if (options.encrypted) { |
| 372 | // Protocol 3.1 and below, only encrypt data if necessary |
| 373 | payload = this.cipher.encrypt({ |
| 374 | data: payload |
| 375 | }); |
| 376 | |
| 377 | // Create MD5 signature |
| 378 | const md5 = this.cipher.md5('data=' + payload + |
| 379 | '||lpv=' + this.version + |
| 380 | '||' + this.key); |
| 381 | |
| 382 | // Create byte buffer from hex data |
| 383 | payload = Buffer.from(this.version + md5 + payload); |
| 384 | } |
| 385 | |
| 386 | // Allocate buffer with room for payload + 24 bytes for |
| 387 | // prefix, sequence, command, length, crc, and suffix |
| 388 | const buffer = Buffer.alloc(payload.length + 24); |
| 389 | |
| 390 | // Add prefix, command, and length |
| 391 | buffer.writeUInt32BE(0x000055AA, 0); |
| 392 | buffer.writeUInt32BE(options.commandByte, 8); |
| 393 | buffer.writeUInt32BE(payload.length + 8, 12); |
| 394 | |
| 395 | if (options.sequenceN) { |
| 396 | buffer.writeUInt32BE(options.sequenceN, 4); |
| 397 | } |
| 398 | |
| 399 | // Add payload, crc, and suffix |
| 400 | payload.copy(buffer, 16); |
| 401 | const calculatedCrc = crc(buffer.slice(0, payload.length + 16)) & 0xFFFFFFFF; |
| 402 | |
| 403 | buffer.writeInt32BE(calculatedCrc, payload.length + 16); |
| 404 | buffer.writeUInt32BE(0x0000AA55, payload.length + 20); |
| 405 | |
| 406 | return buffer; |
| 407 | } |