tinygo.org/x/drivers@v0.27.1-0.20240509133757-7dbca2a54349/rtl8720dn/rpc_util.go (about)

     1  package rtl8720dn
     2  
     3  import (
     4  	"fmt"
     5  	"io"
     6  )
     7  
     8  var (
     9  	headerBuf            [4]byte
    10  	readBuf              [4]byte
    11  	startWriteMessageBuf [1024]byte
    12  	payload              [2048]byte
    13  )
    14  
    15  const (
    16  	xVersion = 1
    17  )
    18  
    19  func startWriteMessage(msgType, service, requestNumber, sequence uint32) []byte {
    20  	startWriteMessageBuf[0] = byte(msgType)
    21  	startWriteMessageBuf[1] = byte(requestNumber)
    22  	startWriteMessageBuf[2] = byte(service)
    23  	startWriteMessageBuf[3] = byte(xVersion)
    24  
    25  	startWriteMessageBuf[4] = byte(sequence)
    26  	startWriteMessageBuf[5] = byte(sequence >> 8)
    27  	startWriteMessageBuf[6] = byte(sequence >> 16)
    28  	startWriteMessageBuf[7] = byte(sequence >> 24)
    29  
    30  	return startWriteMessageBuf[:8]
    31  }
    32  
    33  func (r *rtl8720dn) performRequest(msg []byte) {
    34  	crc := computeCRC16(msg)
    35  	headerBuf[0] = byte(len(msg))
    36  	headerBuf[1] = byte(len(msg) >> 8)
    37  	headerBuf[2] = byte(crc)
    38  	headerBuf[3] = byte(crc >> 8)
    39  
    40  	if r.debug {
    41  		fmt.Printf("tx : %2d : ", len(headerBuf))
    42  		dumpHex(headerBuf[:])
    43  		fmt.Printf("\r\n")
    44  	}
    45  
    46  	r.uart.Write(headerBuf[:])
    47  
    48  	if r.debug {
    49  		fmt.Printf("tx : %2d : ", len(msg))
    50  		dumpHex(msg)
    51  		fmt.Printf("\r\n")
    52  	}
    53  	r.uart.Write(msg)
    54  }
    55  
    56  func dumpHex(b []byte) {
    57  	for i := range b {
    58  		if i == 0 {
    59  			fmt.Printf("%02X", b[i])
    60  		} else {
    61  			fmt.Printf(" %02X", b[i])
    62  		}
    63  	}
    64  }
    65  
    66  func (r *rtl8720dn) read() {
    67  	for {
    68  		n, _ := io.ReadFull(r.uart, readBuf[:4])
    69  		if n == 0 {
    70  			continue
    71  		}
    72  
    73  		if r.debug {
    74  			fmt.Printf("rx : %2d : ", n)
    75  			dumpHex(readBuf[:n])
    76  			fmt.Printf("\r\n")
    77  		}
    78  
    79  		length := uint16(readBuf[0]) + uint16(readBuf[1])<<8
    80  		crc := uint16(readBuf[2]) + uint16(readBuf[3])<<8
    81  
    82  		n, _ = io.ReadFull(r.uart, payload[:length])
    83  		if r.debug {
    84  			fmt.Printf("rx : %2d : ", length)
    85  			dumpHex(payload[0:n])
    86  			fmt.Printf("\r\n")
    87  		}
    88  
    89  		n = int(length)
    90  
    91  		crcNew := computeCRC16(payload[:n])
    92  		if g, e := crcNew, crc; g != e {
    93  			fmt.Printf("err CRC16: got %04X want %04X\r\n", g, e)
    94  		}
    95  		if payload[0] == 0x02 || payload[0] == 0x00 {
    96  			return
    97  		}
    98  	}
    99  }