| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081 |
- package i2creg
- import (
- "encoding/binary"
- "fmt"
- "prod2u6400-uartkit/internal/protocol"
- )
- const (
- Address7 byte = 0x2A
- RegDeviceStatus uint16 = 0x0000
- RegResponseOK uint16 = 0x0001
- RegResponseCommand uint16 = 0x0002
- RegResponseStatus uint16 = 0x0003
- RegResponseDetail uint16 = 0x0004
- RegWatchdogSeconds uint16 = 0x0005
- RegWrittenMask uint16 = 0x0006
- RegSnapshotLengthL uint16 = 0x0007
- RegSnapshotLengthH uint16 = 0x0008
- RegCommand uint16 = 0x0010
- RegStagingBase uint16 = 0x0100
- RegSnapshotBase uint16 = 0x0200
- )
- type Transaction struct {
- Address7 byte
- Write []byte
- ReadLength int
- RepeatedStart bool
- }
- func pointer(reg uint16) []byte {
- var p [2]byte
- binary.BigEndian.PutUint16(p[:], reg)
- return p[:]
- }
- func SetAllTransactions(s protocol.SetAll) ([]Transaction, error) {
- p, err := s.Payload()
- if err != nil {
- return nil, err
- }
- w := append(pointer(RegStagingBase), p...)
- c := append(pointer(RegCommand), protocol.TypeSetAll)
- return []Transaction{{Address7: Address7, Write: w}, {Address7: Address7, Write: c}}, nil
- }
- func GetSnapshotTransactions() []Transaction {
- return []Transaction{{Address7: Address7, Write: append(pointer(RegCommand), protocol.TypeGetSnapshot)}}
- }
- func ReadRegister(reg uint16, n int) Transaction {
- return Transaction{Address7: Address7, Write: pointer(reg), ReadLength: n, RepeatedStart: true}
- }
- func SnapshotReads(length uint16, chunk int) ([]Transaction, error) {
- if chunk <= 0 {
- return nil, fmt.Errorf("chunk must be positive")
- }
- if length == 0 {
- return nil, nil
- }
- result := make([]Transaction, 0, (int(length)+chunk-1)/chunk)
- for off := 0; off < int(length); off += chunk {
- n := chunk
- if rem := int(length) - off; rem < n {
- n = rem
- }
- result = append(result, ReadRegister(RegSnapshotBase+uint16(off), n))
- }
- return result, nil
- }
- type Response struct{ OK, Command, Status, Detail byte }
- func DecodeResponse(regs []byte) (Response, error) {
- if len(regs) < 4 {
- return Response{}, fmt.Errorf("response requires 4 bytes")
- }
- return Response{OK: regs[0], Command: regs[1], Status: regs[2], Detail: regs[3]}, nil
- }
|