| | |
| | | if (!this.client.destroyed) { |
| | | // 原始字符串 |
| | | const originalString = str; |
| | | // 将字符串转换为 Buffer |
| | | const buffer = Buffer.from(originalString); |
| | | console.log(buffer) |
| | | console.log(buffer.length) |
| | | // 获取校验码 |
| | | const checksum = calculateChecksum2(buffer); |
| | | // 将校验码转换为两位十六进制字符串 |
| | | const checksumHex = checksum.toString(16).padStart(2, '0').toUpperCase(); |
| | | // 输出结果 |
| | | console.log(`Checksum (Hexadecimal): ${checksumHex}`); |
| | | // 将校验码追加到原始 Buffer |
| | | const zuijia = Buffer.concat([buffer, Buffer.from([checksum])]); |
| | | console.log('----') |
| | | console.log(zuijia[0], zuijia[zuijia.length - 1]) |
| | | console.log('33333') |
| | | // 计算CRC-16校验码 |
| | | const crcResult = crc16(originalString); |
| | | // 将结果转换为字节数组 |
| | | const crcBytes = [ |
| | | (crcResult >> 8) & 0xFF, // 高字节 |
| | | crcResult & 0xFF // 低字节 |
| | | ]; |
| | | // 创建包含校验码的数据包(先转换为Buffer) |
| | | const messageBuffer = Buffer.concat([ |
| | | Buffer.from(originalString), // 原始数据部分 |
| | | Buffer.from(crcBytes), // CRC校验码部分 |
| | | Buffer.from([0x0D,0x0A]) |
| | | ]); |
| | | console.log('ping hao d jiao yan ma',messageBuffer.length) |
| | | if( this.waitingForAck){ |
| | | console.log('londion-------zhong') |
| | | const listData = { ip: this.host, prot: this.port, data: '正在等待应答中,会自动尝试10秒后发送' } |
| | | fanhuiCommLog(listData) |
| | | }else{ |
| | | console.log('fa song xue ya shu ju ') |
| | | this.sendAndAwaitAck(zuijia) |
| | | this.sendAndAwaitAck(messageBuffer) |
| | | } |
| | | } else { |
| | | return |
| | |
| | | // 如果需要,可以对 sum 取模以适应单个字节 |
| | | return sum & 0xFF; |
| | | } |
| | | /** |
| | | * CRC-16-CCITT(多项式 0x1021)来计算校验码。 |
| | | */ |
| | | function crc16(data) { |
| | | let crc = 0xFFFF; // 初始值 |
| | | let polynomial = 0x1021; // 使用的多项式 |
| | | for (let i = 0; i < data.length; i++) { |
| | | let byte = data.charCodeAt(i); |
| | | crc ^= byte << 8; |
| | | for (let j = 0; j < 8; j++) { |
| | | if ((crc & 0x8000) > 0) { |
| | | crc = (crc << 1) ^ polynomial; |
| | | } else { |
| | | crc = crc << 1; |
| | | } |
| | | } |
| | | crc &= 0xFFFF; // 确保结果为16位 |
| | | } |
| | | |
| | | return crc >>> 0; // 转换为无符号整数 |
| | | } |
| | | /**解析数据1 */ |
| | | function parseData(buf: Uint8Array, index1: number, index2: number, index3: number, index4: number): number { |
| | | let data5: number = (buf[index1] << 24) | (buf[index2] << 16) | (buf[index3] << 8) | buf[index4]; |