MCPcopy Create free account
hub / github.com/codetheweb/tuyapi / _encode34

Method _encode34

lib/message-parser.js:419–469  ·  view source on GitHub ↗

* Encodes a payload into a Tuya-protocol-complient packet for protocol version 3.4 * @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 {Number} options.

(options)

Source from the content-addressed store, hash-verified

417 * @returns {Buffer} Encoded Buffer
418 */
419 _encode34(options) {
420 let payload = options.data;
421
422 if (options.commandByte !== CommandType.DP_QUERY &&
423 options.commandByte !== CommandType.HEART_BEAT &&
424 options.commandByte !== CommandType.DP_QUERY_NEW &&
425 options.commandByte !== CommandType.SESS_KEY_NEG_START &&
426 options.commandByte !== CommandType.SESS_KEY_NEG_FINISH &&
427 options.commandByte !== CommandType.DP_REFRESH) {
428 // Add 3.4 header
429 // check this: mqc_very_pcmcd_mcd(int a1, unsigned int a2)
430 const buffer = Buffer.alloc(payload.length + 15);
431 Buffer.from('3.4').copy(buffer, 0);
432 payload.copy(buffer, 15);
433 payload = buffer;
434 }
435
436 // ? if (payload.length > 0) { // is null messages need padding - PING work without
437 const padding = 0x10 - (payload.length & 0xF);
438 const buf34 = Buffer.alloc((payload.length + padding), padding);
439 payload.copy(buf34);
440 payload = buf34;
441 // }
442
443 payload = this.cipher.encrypt({
444 data: payload
445 });
446
447 payload = Buffer.from(payload);
448
449 // Allocate buffer with room for payload + 24 bytes for
450 // prefix, sequence, command, length, crc, and suffix
451 const buffer = Buffer.alloc(payload.length + 52);
452
453 // Add prefix, command, and length
454 buffer.writeUInt32BE(0x000055AA, 0);
455 buffer.writeUInt32BE(options.commandByte, 8);
456 buffer.writeUInt32BE(payload.length + 0x24, 12);
457
458 if (options.sequenceN) {
459 buffer.writeUInt32BE(options.sequenceN, 4);
460 }
461
462 // Add payload, crc, and suffix
463 payload.copy(buffer, 16);
464 const calculatedCrc = this.cipher.hmac(buffer.slice(0, payload.length + 16));// & 0xFFFFFFFF;
465 calculatedCrc.copy(buffer, payload.length + 16);
466
467 buffer.writeUInt32BE(0x0000AA55, payload.length + 48);
468 return buffer;
469 }
470
471 /**
472 * Encodes a payload into a Tuya-protocol-complient packet for protocol version 3.5

Callers 1

encodeMethod · 0.95

Calls 2

encryptMethod · 0.80
hmacMethod · 0.80

Tested by

no test coverage detected