tinygo.org/x/drivers@v0.27.1-0.20240509133757-7dbca2a54349/pcf8523/pcf8523_test.go (about) 1 package pcf8523 2 3 import ( 4 "encoding/hex" 5 "testing" 6 "time" 7 "tinygo.org/x/drivers/tester" 8 ) 9 10 func TestDecToBcd_RoundTrip(t *testing.T) { 11 12 for i := 0; i < 60; i++ { 13 a := bcd2bin(bin2bcd(i)) 14 if a != i { 15 t.Logf("not equal: %d != %d", a, i) 16 t.FailNow() 17 } 18 } 19 } 20 21 func TestDevice_Reset(t *testing.T) { 22 bus := tester.NewI2CBus(t) 23 fake := bus.NewDevice(DefaultAddress) 24 25 dev := New(bus) 26 27 err := dev.Reset() 28 assertNoError(t, err) 29 30 assertEquals(t, fake.Registers[rControl1], 0x58) 31 } 32 33 func TestDevice_SetPowerManagement(t *testing.T) { 34 bus := tester.NewI2CBus(t) 35 fake := bus.NewDevice(DefaultAddress) 36 37 dev := New(bus) 38 39 err := dev.SetPowerManagement(PowerManagement_SwitchOver_ModeStandard) 40 assertNoError(t, err) 41 42 assertEquals(t, fake.Registers[rControl3], 0b100<<5) 43 } 44 45 func TestDevice_SetTime(t *testing.T) { 46 bus := tester.NewI2CBus(t) 47 fake := bus.NewDevice(DefaultAddress) 48 49 dev := New(bus) 50 51 pointInTime, _ := time.Parse(time.RFC3339, "2023-09-12T22:35:50Z") 52 err := dev.SetTime(pointInTime) 53 assertNoError(t, err) 54 55 actual := hex.EncodeToString(fake.Registers[rSeconds : rSeconds+7]) 56 expected := "50352212020923" 57 assertEquals(t, actual, expected) 58 } 59 60 func TestDevice_ReadTime(t *testing.T) { 61 bus := tester.NewI2CBus(t) 62 fake := bus.NewDevice(DefaultAddress) 63 64 expectedPointInTime := time.Date(2023, 9, 12, 17, 55, 42, 0, time.UTC) 65 fake.Registers[rSeconds] = 0x42 66 fake.Registers[rMinutes] = 0x55 67 fake.Registers[rHours] = 0x17 68 fake.Registers[rDays] = 0x12 69 fake.Registers[rMonths] = 0x9 70 fake.Registers[rYears] = 0x23 71 72 dev := New(bus) 73 74 //when 75 actualPointInTime, err := dev.ReadTime() 76 77 //then 78 assertNoError(t, err) 79 assertEquals(t, actualPointInTime, expectedPointInTime) 80 } 81 82 func assertNoError(t testing.TB, e error) { 83 if e != nil { 84 t.Fatalf("unexpected error: %v", e) 85 } 86 } 87 func assertEquals[T comparable](t testing.TB, a, b T) { 88 if a != b { 89 t.Fatalf("%v != %v", a, b) 90 } 91 }