func TestPutCharacteristic(t *testing.T) {
	info := model.Info{
		Name:         "My Switch",
		SerialNumber: "001",
		Manufacturer: "Google",
		Model:        "Bridge",
	}

	a := accessory.NewSwitch(info)
	a.SetOn(false)

	m := container.NewContainer()
	m.AddAccessory(a.Accessory)

	// find on characteristic with type CharTypePowerState
	var cid int64
	for _, s := range a.Accessory.Services {
		for _, c := range s.Characteristics {
			if c.Type == characteristic.CharTypePowerState {
				cid = c.ID
			}
		}
	}

	if cid == 0 {
		t.Fatal("characteristic not found")
	}

	char := data.Characteristic{AccessoryID: 1, ID: cid, Value: true}
	var slice []data.Characteristic
	slice = append(slice, char)

	chars := data.Characteristics{Characteristics: slice}
	b, err := json.Marshal(chars)

	if err != nil {
		t.Fatal(err)
	}

	var buffer bytes.Buffer
	buffer.Write(b)

	controller := NewCharacteristicController(m)
	err = controller.HandleUpdateCharacteristics(&buffer, characteristic.TestConn)

	if err != nil {
		t.Fatal(err)
	}

	if is, want := a.IsOn(), true; is != want {
		t.Fatalf("is=%v want=%v", is, want)
	}
}
Esempio n. 2
0
func main() {
	switchInfo := model.Info{
		Name: "Lamp",
	}
	sw := accessory.NewSwitch(switchInfo)

	config := hap.Config{Pin: "12344321", Port: "12345", StoragePath: "./db"}
	t, err := hap.NewIPTransport(config, sw.Accessory)

	if err != nil {
		log.Fatal(err)
	}

	// Log to console when client (e.g. iOS app) changes the value of the on characteristic
	sw.OnStateChanged(func(on bool) {
		if on == true {
			log.Println("[INFO] Client changed switch to on")
		} else {
			log.Println("[INFO] Client changed switch to off")
		}
	})

	// Periodically toggle the switch's on characteristic
	go func() {
		for {
			on := !sw.IsOn()
			if on == true {
				log.Println("[INFO] Switch on")
			} else {
				log.Println("[INFO] Switch off")
			}
			sw.SetOn(on)
			time.Sleep(5 * time.Second)
		}
	}()

	hap.OnTermination(func() {
		t.Stop()
	})

	t.Start()
}