i2creg.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. package i2creg
  2. import (
  3. "encoding/binary"
  4. "fmt"
  5. "prod2u6400-uartkit/internal/protocol"
  6. )
  7. const (
  8. Address7 byte = 0x2A
  9. RegDeviceStatus uint16 = 0x0000
  10. RegResponseOK uint16 = 0x0001
  11. RegResponseCommand uint16 = 0x0002
  12. RegResponseStatus uint16 = 0x0003
  13. RegResponseDetail uint16 = 0x0004
  14. RegWatchdogSeconds uint16 = 0x0005
  15. RegWrittenMask uint16 = 0x0006
  16. RegSnapshotLengthL uint16 = 0x0007
  17. RegSnapshotLengthH uint16 = 0x0008
  18. RegCommand uint16 = 0x0010
  19. RegStagingBase uint16 = 0x0100
  20. RegSnapshotBase uint16 = 0x0200
  21. )
  22. type Transaction struct {
  23. Address7 byte
  24. Write []byte
  25. ReadLength int
  26. RepeatedStart bool
  27. }
  28. func pointer(reg uint16) []byte {
  29. var p [2]byte
  30. binary.BigEndian.PutUint16(p[:], reg)
  31. return p[:]
  32. }
  33. func SetAllTransactions(s protocol.SetAll) ([]Transaction, error) {
  34. p, err := s.Payload()
  35. if err != nil {
  36. return nil, err
  37. }
  38. w := append(pointer(RegStagingBase), p...)
  39. c := append(pointer(RegCommand), protocol.TypeSetAll)
  40. return []Transaction{{Address7: Address7, Write: w}, {Address7: Address7, Write: c}}, nil
  41. }
  42. func GetSnapshotTransactions() []Transaction {
  43. return []Transaction{{Address7: Address7, Write: append(pointer(RegCommand), protocol.TypeGetSnapshot)}}
  44. }
  45. func ReadRegister(reg uint16, n int) Transaction {
  46. return Transaction{Address7: Address7, Write: pointer(reg), ReadLength: n, RepeatedStart: true}
  47. }
  48. func SnapshotReads(length uint16, chunk int) ([]Transaction, error) {
  49. if chunk <= 0 {
  50. return nil, fmt.Errorf("chunk must be positive")
  51. }
  52. if length == 0 {
  53. return nil, nil
  54. }
  55. result := make([]Transaction, 0, (int(length)+chunk-1)/chunk)
  56. for off := 0; off < int(length); off += chunk {
  57. n := chunk
  58. if rem := int(length) - off; rem < n {
  59. n = rem
  60. }
  61. result = append(result, ReadRegister(RegSnapshotBase+uint16(off), n))
  62. }
  63. return result, nil
  64. }
  65. type Response struct{ OK, Command, Status, Detail byte }
  66. func DecodeResponse(regs []byte) (Response, error) {
  67. if len(regs) < 4 {
  68. return Response{}, fmt.Errorf("response requires 4 bytes")
  69. }
  70. return Response{OK: regs[0], Command: regs[1], Status: regs[2], Detail: regs[3]}, nil
  71. }