package protocol import ( "fmt" "hash/crc32" "strconv" "time" ) // F1B0 起始帧 // 0000 附加码 // 0006 长度 // 0001 序列号 // 99014C000219 设备id // 10 忽略 // 00 忽略 // 00ED88621203 忽略 // 62D81046 校验位 //[104 101 108 108 111 32 119 111 114 100 32 54 55] // 回复帧 // F1B0 起始帧 // 0000 固定不变 // 0000 固定不变 // 0001 同接收信息的 序列号 // 60580F13 当前时间转16进制 // FFFFFF80 固定不变 // 5CD5D5A2 检验位 // CRC采用CRC32校验算法,校验多项式:x32+x26+x23+x22+x16+x12+x11+x10+x8+x7+x5+x4+x2+x+1,具体算法参考http://www.ip33.com/crc.html,参数模块选择CRC32 // java 代码参考 // import java.util.zip.CRC32; // public static String calcCrc32(byte[] bytes) { // CRC32 crc32 = new CRC32(); // crc32.update(bytes); // return StringUtils.leftPad(Long.toHexString(crc32.getValue()), 8, "0").toUpperCase(); // } // 16进制 func CRC32(data []byte) string { return fmt.Sprintf("%X", crc32.ChecksumIEEE(data)) } func Hex2Dec(val string) int { n, err := strconv.ParseUint(val, 16, 32) if err != nil { fmt.Println(err) } return int(n) } func createTime() string { return fmt.Sprintf("%X", time.Now().Unix()) } func ResponseMessage(input []byte) []byte { response := Hextob("F1B000000000") // 序列号 response = append(response, input[6:8]...) response = append(response, Hextob(createTime())...) response = append(response, Hextob("FFFFFF80")...) response = append(response, Hextob(CRC32(response))...) return response } var num int64 = 200 func CreateCommandMessage() []byte { response := Hextob("F1B5FF000000") num += 1 if num > 1000 { num = 200 } num16 := strconv.FormatInt(num, 16) if len(num16) < 4 { for len(num16)-4 < 0 { num16 = "0" + num16 } } response = append(response, Hextob(num16)...) response = append(response, Hextob(createTime())...) response = append(response, Hextob("FFFFFF804B9888D3")...) return response } func Hextob(str string) []byte { slen := len(str) bHex := make([]byte, len(str)/2) ii := 0 for i := 0; i < len(str); i = i + 2 { if slen != 1 { ss := string(str[i]) + string(str[i+1]) bt, _ := strconv.ParseInt(ss, 16, 32) bHex[ii] = byte(bt) ii = ii + 1 slen = slen - 2 } } return bHex } /*字节数组转16进制可以直接使用 fmt自带的*/ func BytetoH(b []byte) (H string) { H = fmt.Sprintf("%X", b) return }